React apollo client: Warning: Can't perform a React state update on an unmounted component
Asked Answered
J

1

19

I'm using react router and apollo client (v 3.0) in my react project. I have a nested route, let's say A -> B, where I use useQuery hooks to fetch different sets of data via graphql queries, let's say QA and QB respectively. In B I receive a new message via WS about a new piece of data from QB, so I update apollo store cache via client.writeQuery for QB, however this piece of data also contains a nested entity that requested in QA, so this cache update not only triggers rerender of components with useQuery hook of QB but also QA, which produces the following warning:

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.

I added the following debug to the B component:

console.log('WRITE');
client.writeQuery(...)

and to the A component:

useEffect(() => {
  console.log('MOUNT');
  return () => {
    console.log('UNMOUNT');
  };
}, []);

and got:

WRITE
UNMOUNT
MOUNT

So component A unmounts after I update cache via client.writeQuery.

Why does this happen and how to fix that?

Juttajutty answered 16/7, 2020 at 15:54 Comment(2)
Could you provide more source code? It's kinda hard to imagine your use case.Strength
Could you show the way you attach the listener to WS message event?Selfcontrol
S
1

You can safely ignore this warning, it has been removed in React 18.

https://github.com/reactwg/react-18/discussions/82

Stradivari answered 26/7, 2022 at 11:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.