我收到以下错误:“警告:无法对未安装的组件执行React状态更新。这是一个no op,但表示应用程序内存泄漏。若要修复,请取消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]);
哪里有内存泄漏?我能够渲染我的组件没有axios返回语句,但我仍然得到内存泄漏警告。
使用axios包装器的Json获取示例(实时演示)
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>;
}