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

后端 未结 3 1961
野性不改
野性不改 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条回答
  •  猫巷女王i
    2020-12-29 03:28

    For me, clean the state in the unmount of the component helped.

     const [state, setState] = useState({});
    
    useEffect(() => {
        myFunction();
        return () => {
          setState({}); // This worked for me
        };
    }, []);
    
    const myFunction = () => {
        setState({
            name: 'Jhon',
            surname: 'Doe',
        })
    }
    
    

提交回复
热议问题