Reputation: 49
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);
Upvotes: 1
Views: 3361
Reputation: 356
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])
Upvotes: 1