![](/img/trans.png)
[英]Warning: Can't perform a React state update on an unmounted component. useEffect cleanup function
[英]Getting 'Can't perform a React state update on an unmounted component' before useEffect cleanup function executes
在調用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: {});
使用useLayoutEffect
而不是useEffect
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.