Muhammad Usman
Muhammad Usman

Reputation: 19

How to Resolve "Can't perform a React state update on an unmounted component". React Native

ERROR 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.

   useEffect(() => {
     userIsRegister();
     if (sendMessage === '') {
       getAllMessage();
     }
    }, [sendMessage, isFocused]);

Upvotes: 0

Views: 5887

Answers (1)

user1672994
user1672994

Reputation: 10849

As error indicates, the react is being updated while component is already unmounted. It seems that some async task is returned after component is unmounted.

As mentioned in error, you can find out those and used the useEffect's clean-up method. Another way can be to useRef variable to maintain the component mounted state and execute the useEffect body only if component is still mounted.

  // A flag to make sure that the component is still mounted before updating the state for async operation.
  const isComponentMounted = useRef(false);
  useEffect(() => {
    isComponentMounted.current = true;
    return () => {
      isComponentMounted.current = false;
    };
  }, []);

  useEffect(() => {
     if (isComponentMounted.current) {
        userIsRegister();
        if (sendMessage === '') {
          getAllMessage();
        }
      }
  }, [sendMessage, isFocused]);

Upvotes: 1

Related Questions