![](/img/trans.png)
[英]React Warning: Can't perform a React state update on an unmounted component. To fix, cancel all subscriptions
[英]Warning: Can't perform a React state update on an unmounted component. In a functional component
我有一個功能組件,我從 localStorage 獲取一個值並使用該值在 state 中設置一個值:
localforage.getItem<string>('sortType').then((value) => {
setSortType(value)
})
const [sortType, setSortType] = useState('release_date');
當我運行該組件時,我得到一個日志:
警告:無法對未安裝的組件執行 React state 更新。 這是一個空操作,但它表明您的應用程序中存在 memory 泄漏。 要修復,請取消 useEffect 清理中的所有訂閱和異步任務 function。
我讀到發生這種情況是因為我在 state 上使用異步方法localforage.getItem
。但是我還沒有找到可以在功能組件中工作的解決方案。
您在 promise 解析后設置 state,這會導致此代碼在組件卸載后運行。
要解決此問題,您可以在設置 state 之前檢查組件是否仍然已安裝:
const isMountedRef = useRef(true)
useEffect(() => () => { isMountedRef.current = false }, [])
由於依賴數組為空,因此在組件掛載時調用 effect,在組件卸載時執行回調
// somewhere in your code later
localforage.getItem<string>('sortType').then((value) => {
if (isMountedRef.current) {
setSortType(value)
}
})
嘗試使用 React.useEffect 從 localStorage 運行一次 sortType,如下所示:
const [sortType, setSortType] = useState('release_date');
React.useEffect(() => {
localforage.getItem<string>('sortType').then((value) => {
setSortType(value)
})
}, []);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.