【问题标题】:React state update on an unmounted component在未安装的组件上反应状态更新
【发布时间】:2020-09-01 23:41:53
【问题描述】:

我是 react native 的新手,我有一个我无法理解的错误,控制台发送一条消息说

警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要解决此问题,请取消 %s 中的所有订阅和异步任务。%s,一个 useEffect 清理函数

我的代码是下一个

const AuthStack = createStackNavigator();

const LoginStack = () => {

    const initialLoginState = {
        isLoading: true,
        userName: null,
        userToken: null,
    };

    const loginReducer = (prevState, action) => {
        switch (action.type) {
            case 'RETRIEVE_TOKEN':
                return {
                    ...prevState,
                    userToken: action.token,
                    isLoading: false,
                };
            case 'LOGIN':
                return {
                    ...prevState,
                    userName: action.id,
                    userToken: action.token,
                    isLoading: false,
                };  
            case 'LOGOUT':
                return {
                    ...prevState,
                    userName: null,
                    userToken: null,
                    isLoading: false,
                };
        }
    };
    
    const [loginState, dispatch] = useReducer(loginReducer, initialLoginState);

    const authContext = useMemo(() => ({
        signIn: (userName, password) => {
            let userToken;
            userName = null;
            if ( userName == 'user' && password == 'pass' ) {
                userToken: 'irais';
            }
            dispatch({ type: 'LOGIN', id: userName, token: userToken });
        },
        signOut: () => {
            dispatch({ type: 'LOGOUT' });
        },
    }));

    useEffect(() => {
        setTimeout(() => {
            // setIsLoading(false)
            dispatch({ type: 'RETRIEVE_TOKEN', token: 'irais' });
        },1000);
    }, []); 
}

【问题讨论】:

    标签: react-native react-hooks use-effect react-state


    【解决方案1】:

    问题是“useEffect”。您需要返回一个清理函数以确保正确处理所有效果。

     useEffect(() => {
            const handle = setTimeout(() => {
                // setIsLoading(false)
                dispatch({ type: 'RETRIEVE_TOKEN', token: 'irais' });
            },1000);
            
            return () => clearTimeout(handle);
        }, []); 
    

    【讨论】:

      【解决方案2】:

      看看你的useEffect。 它安排一个异步任务(超时)来更新组件状态(使用dispatch)。 然后,您的组件可能在此超时已满时已安装。 解决方法是使用清理函数,基本就是useEffect的return语句:

         useEffect(() => {
              const timeout = setTimeout(() => {
                  // setIsLoading(false)
                  dispatch({ type: 'RETRIEVE_TOKEN', token: 'irais' });
              },1000);
      
              return () => {
                 clearTimeout(timeout);
              }
          }, []);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-14
        • 1970-01-01
        • 2020-11-17
        • 1970-01-01
        • 2020-08-28
        • 2021-12-31
        • 1970-01-01
        • 2021-12-09
        相关资源
        最近更新 更多