【发布时间】:2021-07-05 06:44:17
【问题描述】:
我收到类似警告
Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
我正在使用此代码进行 useEffect 清理,但我仍然收到相同的警告。
useEffect(() => {
let isMounted = true;
if (isMounted) {
displayData();
}
return () => { isMounted = false };
}, []);
const displayData = async () => {
try {
let userToken = await AsyncStorage.getItem('userToken');
setToken(userToken);
}
catch (error) {
//console.log(error);
}
}
有什么办法吗?
【问题讨论】:
-
我想你最好显示displayData函数代码。它有 setState 调用吗?
-
为什么需要一个ismounted boolean,调用displayData,只会调用一次。
-
@DeepinderSingh 我正在使用 ismounted boolea 进行 useEffect 清理。
-
@venomous31 你没有做任何清理,当 useEffect 没有 [] 使用时,这将很有用,你的 useffect 只在 init 上调用一次,所以你在这里并不需要这个。如果 is 没有 '[]' 那么这将很有用。
-
@DeepinderSingh 不工作。
标签: reactjs react-native react-hooks