我编写了一个 ReactJS Web 应用程序。这是一个单页应用程序 (SPA)。 我有一个包含多个页面的菜单。每个页面都是一个 .js 文件。 由于 SPA,当我在菜单中更改页面时,我的浏览器无法刷新整个页面。
这是我放在每一页上的内容:
const myPageLoad = useCallback(async () => {
// loading data
}, []);
useEffect(() => {
myPageLoad();
}, [myPageLoad]);
“加载数据”可能需要 3-4 秒才能加载数据。 它工作正常。
如果我决定在“加载数据”完成之前从菜单中更改页面,我会在 javascript 控制台中收到此警告:
<块引用>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. in Data (created by Context.Consumer)
如果我检测到页面更改,我想我必须取消我的加载特性。但我该怎么做?
非常感谢
答案 0 :(得分:0)
您可以使用 abort
,我通过这种方式修复此类错误:
useEffect(() => {
// get abortion variables
let abortController = new AbortController();
let aborted = abortController.signal.aborted; // true || false
async function fetchResults() {
let response = await fetch(`[WEBSITE LINK]`);
let data = await response.json();
aborted = abortController.signal.aborted; // before 'if' statement check again if aborted
if (aborted === false) {
// Make sure all your 'set states' inside this kind of 'if' statement
setState(data);
}
}
fetchResults();
// make sure to return this abort()
return () => {
abortController.abort();
};
}, [])
其他方法:https://medium.com/wesionary-team/how-to-fix-memory-leak-issue-in-react-js-using-hook-a5ecbf9becf8