React useEffect causing: Can't perform a React state update on an unmounted component

后端 未结 3 1960
野性不改
野性不改 2020-12-29 03:21

When fetching data I\'m getting: Can\'t perform a React state update on an unmounted component. The app still works, but react is suggesting I might be causing a memory leak

3条回答
  •  灰色年华
    2020-12-29 03:46

    Sharing the AbortController between the fetch() requests is the right approach.
    When any of the Promises are aborted, Promise.all() will reject with AbortError:

    function Component(props) {
      const [fetched, setFetched] = React.useState(false);
      React.useEffect(() => {
        const ac = new AbortController();
        Promise.all([
          fetch('http://placekitten.com/1000/1000', {signal: ac.signal}),
          fetch('http://placekitten.com/2000/2000', {signal: ac.signal})
        ]).then(() => setFetched(true))
          .catch(ex => console.error(ex));
        return () => ac.abort(); // Abort both fetches on unmount
      }, []);
      return fetched;
    }
    const main = document.querySelector('main');
    ReactDOM.render(React.createElement(Component), main);
    setTimeout(() => ReactDOM.unmountComponentAtNode(main), 1); // Unmount after 1ms
    
    
    

提交回复
热议问题