这是用于处理http请求的自定义钩子。 问题是当发送HTTP请求时,以及在等待期间,当显示组件卸载时
** index.js:1警告:无法在已卸载的组件上执行React状态更新。这是空操作,但它表明应用程序中发生内存泄漏。要修复,请取消使用useEffect清理功能中的所有订阅和异步任务。 在Login中(由Context.Consumer创建) **
但是我向axios添加了一个请求取消,当组件卸载时,它仍然取消了请求 它显示以上消息
import Axios from "axios";
import axios from "../../util/axios";
export const useHttpClient = () => {
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(false);
const source = useRef<any>();
const httpClient =useCallback(async (
data: any,
url : string,
method: "post" | "get" | "patch" | "delete",
token: string | null
) => {
source.current = Axios.CancelToken.source();
let response;
setIsLoading(true);
let headers;
if (token) {
headers = {
Authorization: "Bearer " + token,
};
}
try {
response = await axios({url,method, data, headers , cancelToken : source.current.token});
setIsLoading(false);
return response;
} catch (err) {
if(Axios.isCancel(err)) console.log("Axios error");
setError("Something went wrong");
setIsLoading(false);
throw new Error("Something went wrong");
}
},[]);
useEffect(()=>{
return ()=>{
if(source.current) source.current.cancel();
}
},[])
const resetError = () => {
setError(null);
};
const resetLoading = () => {
setIsLoading(false);
};
return [error, resetError, isLoading, resetLoading, httpClient] as const;
};