React 原生 useEffect 清理功能

时间:2021-07-05 06:44:17

标签: reactjs react-native react-hooks

我收到类似警告 Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

我正在使用此代码进行 useEffect 清理,但仍然收到相同的警告。

useEffect(() => {
        let isMounted = true;
        
        if (isMounted) {
            displayData();
        }
        
        return () => { isMounted = false };
    }, []);

const displayData = async () => {
        try {
            let userToken = await AsyncStorage.getItem('userToken');
            setToken(userToken);
        }
        catch (error) {
            //console.log(error);
        }
}

有什么解决办法吗?

1 个答案:

答案 0 :(得分:0)

您的警告是Can't perform a React state update on an unmounted component.

因为 AsyncStorage.getItem 是异步的,所以组件在解析一个值时有可能已经卸载。

如果您尝试使用 AsyncStorage.getItem 解析的值设置组件的状态(并且在组件已卸载之后发生),您会收到此警告。

貌似 AsyncStorage.getItem 没有取消的机制,所以要注意异步 AsyncStorage.getItem 解析其值后的后续状态设置。

import React, { useState, useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';

export default function App() {
  const [token, setToken] = useState('');

  useEffect(() => {
    let isMounted = true;

    const displayData = async () => {
      try {
        let userToken = await AsyncStorage.getItem('userToken');
        if (isMounted) {
          setToken(userToken);
        }
      } catch (error) {
      //console.log(error);
      }
    };


    displayData();

    return () => {
      isMounted = false;
    };
  }, []);

  return (
    <>...</>
  );
}

Snack