[英]Can't perform a React state update on an unmounted component with useEffect hook
[英]React UseEffect unmounted component
我收到以下錯誤:“警告:無法在未安裝的組件上執行 React state 更新。這是一個無操作,但它表明您的應用程序中存在 memory 泄漏。要修復,取消所有訂閱和異步任務使用效果清理 function。 "
我的 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]);
我在哪里有 memory 泄漏? 我可以在沒有 axios 返回語句的情況下渲染我的組件,但我仍然收到 memory 泄漏警告。
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.