gpt4 book ai didi

reactjs - React useCallback 内存泄漏卸载组件

转载 作者:行者123 更新时间:2023-12-04 00:13:17 26 4
gpt4 key购买 nike

我是 React 的新手,我收到了这个错误:

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.


据我了解,似乎我有内存泄漏并且需要对我的 useCallback Hook 进行 useEffect 清理?
我尝试添加 useRef检查安装,但返回不会将状态更改为 false。

const MyComponent = ({data}) => {
const mounted = useRef(true);
const [loading, setLoading] = useState(false);

const isLoading = useCallback(async () => {
setLoading(true);

if (data) {
console.log('YAY DATA: ', data);
}

return () => {
setLoading(false); // unreachable code
mounted.current = false; // does this do the cleanup?
};
}, [loading]);

return (
//...some component
);
};

export default MyComponent;

最佳答案

如果您执行的异步操作在完成后需要为状态设置一些内容,则必须确保在更新状态之前组件仍处于挂载状态。
为了做到这一点,你尝试这样的事情:

const MyComponent = (props) => {
const mounted = useRef(false);

useEffect(() => {
mounted.current = true; // Will set it to true on mount ...
return () => { mounted.current = false; }; // ... and to false on unmount
}, []);

const [loading, setLoading] = useState(false);
const [data, setData] = useState([]);

const myAsyncCallback = useCallback(async () => {
setLoading(true);

// Await for an async function...
const data = await yourAsyncFunction(...); // Complete with proper code here

// While waiting for yourAsyncFunction to be done,
// It's possible that your component had been unmounted.

// Therefore, you have to check if the component is still mounted before updating states
if (mounted.current) {
setLoading(false);
setData(data);
}
}, []);

return (
//...some component that calls myAsyncCallback
);
};

export default MyComponent;

关于reactjs - React useCallback 内存泄漏卸载组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66554759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com