[英]React UseEffect unmounted component
I get the following error: " 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. "我收到以下错误:“警告:无法在未安装的组件上执行 React state 更新。这是一个无操作,但它表明您的应用程序中存在 memory 泄漏。要修复,取消所有订阅和异步任务使用效果清理 function。 "
And my useEffect hook looks like this using axios:我的 useEffect 钩子使用 axios 看起来像这样:
const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true;
getSomething(new URLSearchParams(props.location.search), cancelToken).then((response: any) => {
const res = response.data;
if(isMounted.current) setState(res);
});
return () => {
isMounted.current = false;
if(!isMounted.current) cancelToken.cancel();
}
}, [props.location.search]);
Where do I have a memory leak?我在哪里有 memory 泄漏? I am able to render my component without the axios return statement, but I still get the memory leak warning.
我可以在没有 axios 返回语句的情况下渲染我的组件,但我仍然收到 memory 泄漏警告。
Json fetching example using axios wrapper ( Live Demo ) Json 使用 axios 包装器获取示例( 现场演示)
import React, { useState } from "react";
import { useAsyncEffect } from "use-async-effect2";
import cpAxios from "cp-axios";
export default function TestComponent(props) {
const [text, setText] = useState("");
useAsyncEffect(
function* () {
setText("fetching...");
const response = yield cpAxios(props.url); // cancellable request
setText(`Success: ${JSON.stringify(response.data)}`);
},
[props.url]
);
return <div>{text}</div>;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.