首页 > 解决方案 > react native,无法对未安装的组件执行 React 状态更新

问题描述

当我登录时,我收到内存泄漏警告“无法在未安装的组件上执行 React 状态更新。这是一个无操作,但它表明您的应用程序中存在内存泄漏。要修复,请取消所有订阅和异步任务在 useEffect 清理功能中"

登录功能

 const onSubmit = () => {
    const checkValid = isValidData();
    if (checkValid) {
      updateState({isLoading: true});
      action
        .login_with_password({
          country_code: countryCode,
          phone_no: phoneNumber,
          password,
        })
        .then(res => {
          console.log(res);
          if (!res.data.ref_code_verified) {
            navigate(strings.nav_referalcode);
          } else if (!res.data.profile_completed) {
            navigate(strings.nav_profile_setUp);
          } else if (res.data.interest_ids.length == 0) {
            navigate(strings.nav_interest);
            updateState({isLoading: false});
          } else if (res.data.strongest_subject == null) {
            navigate(strings.nav_subject);
            updateState({isLoading: false});
          } else if (!res.data.competitive_exam) {
            navigate(strings.nav_exam);
            updateState({isLoading: false});
          } else if (res.data.purchased_plans.length == 0) {
            navigate(strings.nav_purchase_plan);
            updateState({isLoading: false});
          }

          updateState({isLoading: false});
        })
        .catch(error => {
          console.log(error);
          showError(error.message);
          updateState({isLoading: false});
        });
    }
  };

而且我的主页中没有 useEffect 。为什么我会收到这个错误?有人知道怎么修这个东西吗?

标签: reactjsreact-nativereact-hooks

解决方案


问题

您可能会看到此警告,因为您正在将路由转换排队到应用程序中的另一个页面并将状态更新排队。转换发生,组件卸载,然后 React 尝试更新状态但不能。

解决方案

从应用程序路径中删除状态更新调用。返回导航,在不满足条件的情况下保持上次状态更新。

const onSubmit = () => {
  const checkValid = isValidData();
  if (checkValid) {
    updateState({ isLoading: true });
    action
      .login_with_password({
        country_code: countryCode,
        phone_no: phoneNumber,
        password,
      })
      .then(res => {
        console.log(res);
        if (!res.data.ref_code_verified) {
          return navigate(strings.nav_referalcode);
        } else if (!res.data.profile_completed) {
          return navigate(strings.nav_profile_setUp);
        } else if (!res.data.interest_ids.length) {
          return navigate(strings.nav_interest);
        } else if (res.data.strongest_subject === null) {
          return navigate(strings.nav_subject);
        } else if (!res.data.competitive_exam) {
          return navigate(strings.nav_exam);
        } else if (!res.data.purchased_plans.length) {
          return navigate(strings.nav_purchase_plan);
        }

        updateState({ isLoading: false });
      })
      .catch(error => {
        console.log(error);
        showError(error.message);
        updateState({ isLoading: false });
      });
  }
};

推荐阅读