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);
Harry
  • 49
  • 1
  • 8

1 Answers1

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])
Karambit
  • 317
  • 4
  • 11
  • No, i do not have any button in my component. The code works fine but i get warning. – Harry Oct 01 '21 at 14:01
  • @Developer then maybe it could be due to not cancelling the fetch request when the useEffect dependencies change – Karambit Oct 01 '21 at 14:07
  • 1
    @Developer maybe try cancelling the fetch request in the clean up function using AbortController() – Karambit Oct 01 '21 at 14:09
  • 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. – Harry Oct 01 '21 at 14:16