1

I have an issue of memory leak and I get following error in my console.

"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 use Effect cleanup function."

Here is my code:

React.useEffect(() => {
        if (data) {
            // I am calling my fetch method
            fetch(logData)
                .then((response) => response.json())
                .then((data) => {
                    //logic
                    //setState called at end of logic
                    setData(data);
                });
        }
    }, [value);

1 Answer 1

1

Maybe your component is getting unmounted due to some interaction while it is fetching the data ? like by clicking the close button (if your component has one)

to avoid running into this error you can check if your component is mounted like this

const isMounted = useRef(true);
useEffect(() => () => { isMounted.current = false }, [])

and then only setState if the component is still mounted

useEffect(() => {
    fetch(res)
        .then(res => res.json())
        .then((data) => {
            if (isMounted) {
                setState(data)
            }
        })
}, [dep])
Sign up to request clarification or add additional context in comments.

4 Comments

No, i do not have any button in my component. The code works fine but i get warning.
@Developer then maybe it could be due to not cancelling the fetch request when the useEffect dependencies change
@Developer maybe try cancelling the fetch request in the clean up function using AbortController()
Thanks for the help ! I will try above mentioned solution. Since the error do not occur often, I need to wait a bit and check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.