Typescript react native上的未安装组件错误
警告错误:无法对已卸载的组件执行react状态更新 这是一个no-op,但它表示应用程序中存在内存泄漏。要修复,请取消useEffect清理功能中的所有订阅和同步tak 我用它来导航到不同的场景,一旦位置被捕获。但在导航到屏幕后会显示警告Typescript react native上的未安装组件错误,typescript,react-native,Typescript,React Native,警告错误:无法对已卸载的组件执行react状态更新 这是一个no-op,但它表示应用程序中存在内存泄漏。要修复,请取消useEffect清理功能中的所有订阅和同步tak 我用它来导航到不同的场景,一旦位置被捕获。但在导航到屏幕后会显示警告 useEffect ( () => { (async () => { let {status} = await Location.requestPermissionsAsync();
useEffect ( () => {
(async () => {
let {status} = await Location.requestPermissionsAsync();
if (status !== 'granted'){
setErrorMsg('Permission to access location is not granted')
}
let location = await Location.getCurrentPositionAsync({});
const {coords} = location
if (coords) {
const {latitude, longitude} = coords;
let addressResponse: any = await Location.reverseGeocodeAsync({latitude, longitude})
for (let item of addressResponse){
setAddress(item)
let currentAddress = `${item.name},${item.street},${item.postalCode},${item.country}`
setDisplayAddress (currentAddress)
if (currentAddress.length>0){
setTimeout(
() => {
navigate('homeStack')
},1000)
}
return;
}
}else {
}
})();
},)
在调用setState之前,您应该检查组件是否仍然装入,最简单的方法是引入一个标志变量
isMounted
,您将在每次异步函数调用后检查该变量
function Component() {
let isMounted= true;
useEffect ( () => {
(async () => {
let {status} = await Location.requestPermissionsAsync();
if(!isMounted) return; // stop the execution of the function;
if (status !== 'granted'){
setErrorMsg('Permission to access location is not granted')
}
let location = await Location.getCurrentPositionAsync({});
if(!isMounted) return; // stop the execution of the function;
// ...
})
return ()=> (isMounted= false);
}
或者,如果组件卸载,您可以使用自定义实验挂钩自动取消异步序列:
import React, { useState } from "react";
import { useAsyncEffect } from "use-async-effect2";
import { CPromise } from "c-promise2";
export default function TestComponent(props) {
// ...
useAsyncEffect(function* () {
const { status } = yield Location.requestPermissionsAsync();
if (status !== "granted") {
setErrorMsg("Permission to access location is not granted");
}
const { coords } = yield Location.getCurrentPositionAsync({});
if (coords) {
const { latitude, longitude } = coords;
let addressResponse = yield Location.reverseGeocodeAsync({
latitude,
longitude
});
for (let item of addressResponse) {
setAddress(item);
let currentAddress = `${item.name},${item.street},${item.postalCode},${item.country}`;
setDisplayAddress(currentAddress);
if (currentAddress.length > 0) {
yield CPromise.delay(1000); // auto-cancellable delay
navigate("homeStack");
}
return;
}
}
});
}