每當有任何與組件相關的異步任務執行并且該組件卸載時,React 通常會給出這個警告 -
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.
我在互聯網上找到了一些解決方案來使用 isMount 標志(通過將它與 useRef 或 useState 一起使用)作為 true,然后在組件卸載時將其更新為 false。但是,根據 React 站點,使用 isMount 的正確解決方案是一種反模式。
https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html
uj5u.com熱心網友回復:
在未來版本的 React 中,你可能不需要修復這個問題。因為 React 開發團隊將在未來的版本中洗掉這個警告。主要原因是此警告有時可能是誤報。
根據 Dan Abramov 的這個提交 https://github.com/facebook/react/pull/22114
但是在那個版本發布之前解決這個問題的解決方案是什么 -
使用 isMountState 反模式 - 如果有人在他的代碼中檢查 isMounted 以解決此問題,那么該人執行此檢查已經為時已晚,因為此警告表明 React 執行了相同的檢查并且它失敗了。
如果這個問題是因為異步呼叫。然后一種可能的解決方案是在您的代碼中使用 AbortController API。AbortController API 有助于中止任何已經進行的 ajax 呼叫。酷的東西。正確的?
可以在此處找到有關此的更多詳細資訊
中止控制器1
因此,如果它是一個獲取 API,則可以像這樣使用 AbortController API
useEffect(() => {
const abortController = new AbortController()
// creating an AbortController
fetch(url, {
signal: abortController.signal
})
// passing the signal to the query
.then(data => {
setState(data)
// if everything went well, set the state
})
.catch(error => {
if (error.name === 'AbortError') return
// if the query has been aborted, do nothing
throw error
})
return () => {
abortController.abort()
// stop the query by aborting on the AbortController on unmount
}
}, [])
如果您使用的是 axios,那么好訊息是 axios 還提供了對 AbortController API 的支持 -
const fetchData = async (params) => {
setLoading(true);
try {
const result = await axios.request(params);
// more code here
} catch (curError) {
if (axios.isCancel(curError)) {
return false;
}
// error handling code
}
return null;
};
useEffect(() => {
const cancelToken = axios.CancelToken;
const source = cancelToken.source();
fetchData({
...axiosParams,
cancelToken: source.token
});
return () => {
source.cancel("axios request cancelled");
};
}, []);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/432112.html
