javascript - 如果用户未登录,则重定向到主页时出现内存泄漏错误

标签 javascript reactjs asynchronous axios

如果用户未在 componentDidMount 中登录(状态 401),我会尝试重定向到主页。

所以我尝试了

componentDidMount() {
    const requestPatientListApi = async () => {
      try {
        const { data } = await get<AxiosResponse<PatientApi>>("/patient", { requester: "admin" });
        return data.items;
      } catch (err) {
          //when user is not logged in redirect to "./"
          props.history.push("./");
      }
      return [];
    };

    if (!axios.isCancel("")) {
        // updating state when api call is not canceled 
        requestPatientListApi().then(patients => {
          setPatients(patients);
        });
    }
}


  componentWillUnmount() {
      if (cancel) {
        cancel();
      }
  }

但是,出现错误:

Warning: Can't perform a React state update on an unmounted component. 

我尝试过使用 axios 取消 token ,但它似乎不是这种情况的解决方案。 有什么想法吗?

最佳答案

问题是您在设置状态之前进行重定向,在这种情况下,组件将不再呈现。一种方法是在异步函数中转发错误并稍后捕获它。

componentDidMount() {
  const requestPatientListApi = async () => {
    try {
      const { data } = await get <AxiosResponse<PatientApi>>("/patient", {
        requester: "admin"
      });
      return data.items;
    } catch (err) {
      throw err; // Forward the error further
    }
    return [];
  };

  if (!axios.isCancel("")) {
    requestPatientListApi().then(patients => {
      setPatients(patients);
    }).catch(err => {
      props.history.push("/"); // handle the error here
    });
  }
}

关于javascript - 如果用户未登录,则重定向到主页时出现内存泄漏错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57521015/

相关文章:

javascript - React Routing Menu - 数据处理最佳实践

javascript - 在 React 中使用枚举文件中的属性返回标题未定义

json - Q : Correct way posting JSON from Reactstrap form

c# - 如何通过网络请求取消异步任务?

javascript - React 中的异步渲染

javascript - AngularJS 动画卡片翻转

javascript - JavaScript中的多语言警报消息

javascript - React Redux 不传递数据

javascript - 为 HOC 编写流 libdef

python - 从 Tornado 异步调用函数