0

I am not able to unmount this please help, please tell me how to unmount a function in useEffect

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.

        checkLoginState();
    },[]);

    const checkLoginState = () =>{

        if(user.length > 0 ){
          fetch(`${Config.SERVER_KEY}/api/users/profile`, {
            method: 'GET',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${user}`
            }
          }).then((response) => response.json())
            .then((json) => {
              console.log(json)
                if(json.success === true){
                  setUserData(json.data)
                  setData(json)
                  setUser(true)
                  setLoading(false)
                } else if (json.msg === 'Token has expired'){
                  refresh();
                } else {
                  console.log(json)
                  alert('Failed to access data')
                  navigation.navigate('main')
                }
            })
            .catch((error) => {
               console.log(error)
            });
          
        } else {
          setLoading(false)
        }

    }```
Heavell
  • 1
  • 1
  • 1
    Please include the full code and properly format it. I do not see the `useEffect` hook. – yudhiesh Apr 05 '21 at 17:12
  • You usually get that error when you cal `setState` after your component has been unmounted. In your case it seems like your component was unmounted (maybe you navigated back) while the `fetch` call was still happening and when you got the server response, React tries to call `setUserData(json.data)`, `setData(json)`, etc which would explain your error. You can add a check inside your `then` block and only execute that code if the component is mounted or you can also cancel the `fetch` request inside `componentWillUnmount` – Carlos J Apr 05 '21 at 17:15
  • This happens when the component unmounts before the fetch has finished. There are lots of answers and articles on how to deal with this. Essentially you need a boolean value like isSubscribed inside your useEffect and you only call setState functions in your then if isSubscribed is still true. – Linda Paiste Apr 05 '21 at 17:15
  • Does this answer your question? [Can't perform a React state update on an unmounted component](https://stackoverflow.com/questions/53949393/cant-perform-a-react-state-update-on-an-unmounted-component) – yudhiesh Apr 05 '21 at 17:16

0 Answers0