在调用useEffect清理函数之前,我得到警告“无法在已卸载的组件上执行React状态更新”。
此代码:
const [data, setData] = useState({});
useEffect(() => {
doFetch();
return () => { console.log('useEffect cleanup'); };
}, []);
const doFetch = async () => {
const response = await fetchAsync(...);
console.log('about to set state');
setData(response.data);
console.log('did set state');
};
产生控制台输出:
about to set state
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.
did set state
useEffect cleanup
我认为我的清理功能将在组件卸载之前并因此在警告之前执行,但是它将在警告之后执行。因此,通过正确取消异步任务(我已经尝试了),我无法得到警告消失的警告。我怎么能得到这个警告而消失?
如果有什么不同,可以使用ReactDOM.render()和ReactDOM.unmountComponentAtNode()在单元测试中安装和卸载组件。
已将fetchAsync函数存根。const stub = sinon.stub(..., fetchAsync);
stub.returns(Promise.resolve({status: 200, data: {});
答案 0 :(得分:0)
使用useLayoutEffect
代替useEffect