【发布时间】:2021-10-26 09:06:46
【问题描述】:
我知道已经有很多关于这方面的问题,但我已经尝试了所有我能找到的解决方案,但都没有奏效。我正在使用返回图像的 react-redux 执行 API 请求。第一次执行良好,但如果我返回导航堆栈,然后返回执行请求的位置,我会收到以下警告:
Warning: 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.
组件中出现这种情况的代码是:
const image = useSelector((state) => state.images.image);
const dispatch = useDispatch();
const loadImage = useCallback(async () => {
setError(null);
setIsLoading(true);
try {
await dispatch(actions.fetchImage());
} catch (err) {
setError(err.message);
}
setIsLoading(false);
}, [dispatch]);
useEffect(() => {
setIsLoading(true);
loadImage().then(() => {
setIsLoading(false);
});
}, [setIsLoading, loadImage]);
我找到的最有希望的解决方案是这样,但这并没有摆脱错误:
useEffect(() => {
let mounted = true;
setIsLoading(true);
loadImage().then(() => {
if (mounted) {
setIsLoading(false);
}
});
return function cleanup() {
mounted = false;
};
}, [setIsLoading, loadImage]);
有什么想法吗?
【问题讨论】:
标签: react-native react-redux react-hooks use-effect