Rob23
Rob23

Reputation: 51

Why can't perform a React state update on an unmounted component using axios?

What I'm trying to do is to update data using Axios put() method. What I have done by far is using <Link></Link> from react-router-dom to direct the user to the edit component. And in the edit component, I get the clients data by using Axios get() method.(not sure I'm doing the edit logic right atm)

After I do that this error is shown in my console: index.js:1 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.

This is the code in edit component:

  useEffect(() => {
    const playerParams =
      "userName=" +
      currentUser+
      "clientId=" +
      currentClient;
    setClientList([]);
    axios
      .get('API' + playerParams)
      .then((response) => {
        const data = response.data
        setClientList(data);
      })
      .catch((error) => console.log(error));
    
  }, []);

This is how I direct the user ClientList.js

 <Link
  to= {`/client/editclient/${clientList.id}`}
   >
      Edit
 </Link>

How can I solve the error?

Upvotes: 0

Views: 161

Answers (1)

dabyland
dabyland

Reputation: 353

Usually this occurs when you are navigating away from a page that is trying to set some piece of state. Take this scenario for instance:

  • A user clicks on a page that make an asynchronous call which takes 5 seconds (the time is just for sake of explanation)
  • The user then clicks away from that page during the time it takes for the asynchronous call to finish, say the user clicks away 2 seconds into the call.
  • After 3 more seconds, the asynchronous call finally finishes and is able to perform the actions it normally would after success/fail except that component is no longer mounted and can't set it's state.

This is very common and is often circumvented by cancelling the promise via a token, library, or cleanup/unmount effects to cancel the promise in flight. This may or may not be the scenario you are seeing and it's one I have seen plenty in the past. Figured I'd give a little insight on what may be happening so you can double check it's not actually the component you're currently viewing but more so the component you are no longer viewing.

Upvotes: 2

Related Questions