Reactjs React useCallback内存泄漏卸载的组件

Reactjs React useCallback内存泄漏卸载的组件,reactjs,react-native,Reactjs,React Native,我是一个新的反应者,我遇到了以下错误: 警告:无法对已卸载的组件执行React状态更新。这是一个no-op,但它表示应用程序中存在内存泄漏。要修复此问题,请取消useEffect清理函数中的所有订阅和异步任务 据我所知,似乎我有内存泄漏,需要对useCallback挂钩进行useEffect清理 我已经尝试添加一个useRef来检查装载,但是返回值并没有将状态更改为false const MyComponent = ({data}) => { const mounted = useR

我是一个新的反应者,我遇到了以下错误:

警告:无法对已卸载的组件执行React状态更新。这是一个no-op,但它表示应用程序中存在内存泄漏。要修复此问题,请取消useEffect清理函数中的所有订阅和异步任务

据我所知,似乎我有内存泄漏,需要对useCallback挂钩进行useEffect清理

我已经尝试添加一个
useRef
来检查装载,但是返回值并没有将状态更改为false


const MyComponent = ({data}) => {
  const mounted = useRef(true);
  const [loading, setLoading] = useState(false);

  const isLoading = useCallback(async () => {
    setLoading(true);

    if (data) {
      console.log('YAY DATA: ', data);
    }

    return () => {
      setLoading(false); // unreachable code
      mounted.current = false; // does this do the cleanup?
    };
  }, [loading]);

  return (
    //...some component
  );
};

export default MyComponent;


如果执行的异步操作在完成时需要将某些内容设置为状态,则必须确保组件在更新状态之前仍已装入

为此,您可以执行以下操作:

const MyComponent = (props) => {
  const mounted = useRef(false);

  useEffect(() => {
        mounted.current = true; // Will set it to true on mount ...
        return () => { mounted.current = false; }; // ... and to false on unmount
  }, []);

  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);

  const myAsyncCallback = useCallback(async () => {
    setLoading(true);

    // Await for an async function...
    const data = await yourAsyncFunction(...); // Complete with proper code here

    // While waiting for yourAsyncFunction to be done,
    // It's possible that your component had been unmounted.

    // Therefore, you have to check if the component is still mounted before updating states
    if (mounted.current) { 
      setLoading(false);
      setData(data);
    }
  }, []);

  return (
    //...some component that calls myAsyncCallback
  );
};

export default MyComponent;

作为组件卸载时的useEffect cleanUp,您不能更新状态(因为它卸载了可以存储值的位置)

您的代码似乎是在useEffect中进行api调用的代码。如下所示:

useEffect(() => {
    let mounted = true
    fetchAPI.then(() => {
        if (mounted) {
            setloading(false)
        }
    })

    return function cleanup() {
        mounted = false
    }
}, [])
如果是这样,请看这里:

谢谢你给了我解决我自己问题的想法。