Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何修复Reactjs中无法对未安装组件执行React状态更新的警告_Reactjs - Fatal编程技术网

如何修复Reactjs中无法对未安装组件执行React状态更新的警告

如何修复Reactjs中无法对未安装组件执行React状态更新的警告,reactjs,Reactjs,当我运行代码时,我在控制台中得到以下警告 警告:无法对已卸载的组件执行React状态更新。这是一个no-op,但它表示应用程序中存在内存泄漏。要修复此问题,请取消useEffect清理函数中的所有订阅和异步任务 这是我的密码: const [userDetail, setUserDetail] = React.useState(''); const personalDetails = (user_id) => { axios .get(`http://localhos

当我运行代码时,我在控制台中得到以下警告

警告:无法对已卸载的组件执行React状态更新。这是一个no-op,但它表示应用程序中存在内存泄漏。要修复此问题,请取消useEffect清理函数中的所有订阅和异步任务

这是我的密码:

 const [userDetail, setUserDetail] = React.useState('');
  const personalDetails = (user_id) => {
    axios
    .get(`http://localhost:3001/users/${user_id}`, { withCredentials: true })
    .then((response) => {
      const personalDetails = response.data;
      setUserDetail(response.data);
    })
    .catch((error) => {
      console.log(" error", error);
    });
  };
  React.useEffect(() => {
   if (user_id) {
    personalDetails(user_id);
  }
}, [user_id]);

如果删除useEffect调用,此错误将消失。这里出了什么问题?

这似乎是正在发生的事情:

您的组件将挂载。 您的效果运行,开始发出HTTP请求。 无论父组件出于何种原因将其移除,该组件都会卸载。 HTTP请求完成,回调调用setUserDetail,即使组件已卸载。 另一个问题是,您在使用它的效果之外定义personalDetails

我要做两个改变:

将personalDetails函数的主体移动到效果中。 如果组件已卸载,或者用户id已更改,则您不想再调用setUserDetail,因此请使用中止变量来跟踪此情况。
这回答了你的问题吗?让useEffect包装您的api调用代码,而不是相反。因为它是异步的,并且满足竞争条件。阅读本文:如果您在组件函数中使用该函数,还需要使用useCallback钩子包装该函数。如果有子组件使用它,它有助于对记忆做出反应,并避免不必要的重新渲染。感谢您的详细描述。警告现在不见了。非常感谢你帮助我。我是一个新的反应,我在学习阶段。再次感谢
const [userDetail, setUserDetail] = React.useState("");

React.useEffect(() => {
  if (user_id) {
    let aborted = false;

    axios
      .get(`http://localhost:3001/users/${user_id}`, { withCredentials: true })
      .then((response) => {
        const personalDetails = response.data;

        // Don't change state if the component has unmounted or
        // if this effect is outdated
        if (!aborted) {
          setUserDetail(response.data);
        }
      })
      .catch((error) => {
        console.log(" error", error);
      });

    // The function returned here is called if the component unmounts
    // or if the dependency list changes (user_id changes).
    return () => (aborted = true);
  }
}, [user_id]);