简体   繁体   中英

Getting 'Can't perform a React state update on an unmounted component' before useEffect cleanup function executes

I get the warning "Can't perform a React state update on an unmounted component" before the useEffect cleanup function is called.

This code:

const [data, setData] = useState({});

useEffect(() => {
   doFetch();
   return () => { console.log('useEffect cleanup'); };
}, []);

const doFetch = async () => {
   const response = await fetchAsync(...);
   console.log('about to set state');
   setData(response.data);
   console.log('did set state');
};

produces the console output:

about to set state
Warning: 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.
did set state
useEffect cleanup

I would think that my cleanup function would execute before the component unmounts and thus before the warning, but it's executing after the warning. Because of that, I can't get the warning to go away by properly canceling the asynchronous task (which I've tried). How can I get this warning to go away?

If it makes any difference, the component is being mounted and unmounted inside of a unit test using ReactDOM.render() and ReactDOM.unmountComponentAtNode(). The fetchAsync function is being stubbed out with

const stub = sinon.stub(..., fetchAsync);
stub.returns(Promise.resolve({status: 200, data: {});

Use useLayoutEffect instead of useEffect

Read more here

https://kentcdodds.com/blog/useeffect-vs-uselayouteffect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM