首页 > 解决方案 > 无法对未安装的组件执行 React 状态更新。React、redux 和 useEffect 的问题

问题描述

我有一个使用这样的钩子的 React 组件:

const myComponent = (props) => {
  useEffect(() => {
     FetchData()
     .then(data => {
       setState({data: data});
     }
    // some other code
  }, []);

//some other code and render method...
}

fetchData 负责使用 axios 并从 API 获取数据:

const FetchData = async () => {
   try {
    res = await myApiClient.get('/myEndpoint);
   } catch (err) {
    console.log('error in FetchData');
    res = err.response
}
}

最后 myApiClient 是在外部定义的。我必须使用此设置才能使用不同的 API...

import axios from "axios";
axios.defaults.headers.post["Content-Type"] = "application/json";

const myApiClient = axios.create({
  baseURL: process.env.REACT_APP_API1_BASEURL
});
const anotherApiClient = axios.create({
  baseURL: process.env.REACT_APP_API2_BASEURL
});

export {
  myApiClient,
  anotherApiClient
};

使用此设置,我收到警告

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.

我用谷歌搜索了一下,我看到了一些关于如何清理来自 useEffect 的请求的建议,就像这样,但我的 axios 是在外部定义的。那么如何使用此设置发送取消?

此外,该应用程序正在使用 redux,不确定它是否以某种方式涉及。

欢迎任何其他避免错误的建议。

标签: reactjsreduxreact-reduxaxiosreact-hooks

解决方案


您可以为此使用deferfrom :rxjs

const FetchData = () => {
  try {
    return myApiClient.get("/myEndpoint");
  } catch (err) {
    console.log("error in FetchData");
    return err.response;
  }
};

const myComponent = (props) => {
  useEffect(() => {
    const subscription = defer(FetchData()).subscribe({
      next: ({
        data
      }) => {
        setState({
          data: data
        });
      },
      error: () => {
        // error handling
      },
      complete: () => {
        // cancel loading state etc
      }
    });

    return () => subscription.unsubscribe();
  }, []);
}

推荐阅读