简体   繁体   English

React UseEffect 卸载组件

[英]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.

相关问题 无法使用 useEffect 挂钩对未安装的组件执行 React state 更新 - Can't perform a React state update on an unmounted component with useEffect hook 无法使用 useEffect 对未安装的组件问题执行反应状态更新 - can't perform a react state update on an unmounted component issue with useEffect 反应更新未安装的组件 - React updating unmounted component React - 未安装组件上的 setState() - React - setState() on unmounted component 反应组件未安装 - React component unmounted React:“无法在未安装的组件上执行 React 状态更新”没有 useEffect 函数 - React: "Can't perform a React state update on an unmounted component" without useEffect function 无法对未安装的组件执行 React state 更新。 使用效果 React-Native - Can't perform a React state update on an unmounted component. useEffect React-Native React useEffect 导致:无法对未安装的组件执行 React 状态更新 - React useEffect causing: Can't perform a React state update on an unmounted component 在useEffect清理函数执行之前获取“无法对卸载的组件执行React状态更新” - Getting 'Can't perform a React state update on an unmounted component' before useEffect cleanup function executes React - 即使组件已卸载,我也需要执行异步 state 更新和 useEffect - React - I need to perform async state updates and useEffect even if the component has been unmounted
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM