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
報錯提示:無法對未裝載的組件執行反應狀態更新。這是一個不准的操作,但它表示應用程序內存泄漏。若要修復,請取消useffect清理函數中的所有訂閱和異步任務
原因:組件卸載了,但是仍處於渲染數據狀態(如:setState,useState),一般寫定時器時候會有出現。其他情況也會,只要組件卸載但仍在更新數據時機
解決如下:
這個錯誤不大會影響實際使用,解決非常簡單。
先講下hook函數組件的解決:
第一種定時器情況:
const [update, setUpdate] = useState(1);
useEffect(() => { const creatInt = setInterval(() => { //假設這里寫了定時器來更新update setUpdate(c => c + 1); }, 2000); return () => { clearInterval(creatInt); //(重點)這里清除掉定時器 }; }, []);
第二種useSate情況:
useEffect(() => { let isUnmount = false; //這里插入isUnmount const fetchDetail = async () => { const res = await getDetail(detailId); if (res.code === 0 && !isUnmount) { //加上判斷isUnmount才去更新數據渲染組件 setDetail(res.data); } }; fetchDetail(); return () => isUnmount = true; //最好return一個isUnmount }, [detail]);
說明:useEffect相當於class組件的3個生命周期,其中return ()=>{ } 相當於 componentWillUnMount
class類組件:原理同hook在 componentWillUnMount 中設置一個 值true 、false來判斷是否渲染組件