有时我会收到错误,完整的错误消息是: “警告:无法对已卸载的组件执行 React 状态更新。这是一个无操作,但它表明应用程序中存在内存泄漏。要修复此问题,请取消 useEffect 清理函数中的所有订阅和异步任务.”
解决这个问题的最佳方法是什么?这是我的代码:
const CustomRefresh = (props) => {
const {
isCurrent, isScheduled
} = props;
const [refreshing, setRefreshing] = useState(false);
const inventoryContext = useContext(inventoryContext);
const onRefresh = React.useCallback(async () => {
setRefreshing(true);
if (isCurrent) {
await inventoryContext.refreshToday();
}
if (isScheduled) {
await inventoryContext.refreshScheduled();
}
setRefreshing(false);
}, [refreshing]);
return (
<CustomRefresh refreshing={refreshing} style={style} onRefresh={onRefresh}>
{children}
</CustomRefresh>
);
};
最佳答案
添加一个引用来跟踪它是否已卸载。然后在您的函数中检查该引用,然后再设置异步设置状态:
const unmounted = useRef(false);
useEffect(() => {
return () => { unmounted.current = true };
}, []);
const onRefresh = React.useCallback(async () => {
setRefreshing(true);
if (isCurrent) {
await inventoryContext.refreshToday();
}
if (isScheduled) {
await inventoryContext.refreshScheduled();
}
if (!unmounted.current) {
setRefreshing(false);
}
}, [refreshing]);
关于reactjs - 无法在未安装的组件上执行 useCallback 的 React 状态更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66552048/