【问题标题】:Why my firebase "onAuthStateChanged" don't clear from useEffect Hook?为什么我的firebase“onAuthStateChanged”没有从useEffect Hook中清除?
【发布时间】:2021-08-31 14:47:11
【问题描述】:

我从控制台收到此错误“警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请取消 useEffect 清理函数中的所有订阅和异步任务。 这是我的功能:

useEffect(() => {
    let isMounted = true;
    const onSubscribe = () => {
      auth.onAuthStateChanged((userAuth) => {
        if (userAuth && isMounted) {
          dispatch(
            login({
              email: userAuth.email,
              uid: userAuth.uid,
              displayName: userAuth.displayName,
              photoUrl: userAuth.photoURL,
            })
          );
        } else if (!userAuth && isMounted) {
          dispatch(logout());
        }
      });
    };
    onSubscribe();
    return () => {
      isMounted = false;
    };
  }, []);

我也试过这种方法

  useEffect(() => {;
    const onSubscribe = () => {
      auth.onAuthStateChanged((userAuth) => {
        if (userAuth) {
          dispatch(
            login({
              email: userAuth.email,
              uid: userAuth.uid,
              displayName: userAuth.displayName,
              photoUrl: userAuth.photoURL,
            })
          );
        } else if (!userAuth) {
          dispatch(logout());
        }
      });
    };
    onSubscribe();
    return () => {
      onSubscribe()
    };
  }, []);

【问题讨论】:

  • 从第一个示例中删除 isMounted = false; 对您有帮助吗?

标签: reactjs firebase firebase-authentication react-hooks


【解决方案1】:

你可以这样试试吗:


useEffect(() => {
    const unsubscribe =  auth.onAuthStateChanged((userAuth) => {
        if (userAuth && isMounted) {
          dispatch(
            login({
              email: userAuth.email,
              uid: userAuth.uid,
              displayName: userAuth.displayName,
              photoUrl: userAuth.photoURL,
            })
          );
        } else if (!userAuth && isMounted) {
          dispatch(logout());
        }
      });
    
    return unsubscribe;
  }, []);

【讨论】:

    猜你喜欢
    • 2023-02-17
    • 2020-08-27
    • 2021-11-29
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 2021-08-19
    相关资源
    最近更新 更多