Home > Net >  React form submit and "can't perform state update on an unmounted component"?
React form submit and "can't perform state update on an unmounted component"?

Time:10-27

Basically, I have a login page, and when you fill out the form and submit data, it goes through this

const formSubmitHandler = (e) => {
    e.preventDefault();
    
  //validation and other uninteresting stuff...

    axios.post('/signin', { email: inputs.email, password: inputs.password })
    .then(response => {
      localStorage.setItem('token', JSON.stringify(response.data.token));
      addUser({ id: response.data.id, name: response.data.username }); 
      history.push('/');
    })
    .catch(err => setLastError(err.response.data));
  }

And it works, but I get the 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.

So I google the issue, then try adding the axios cancel token, more precisely I set

let source = axios.CancelToken.source();

Then added the following to my axios request

  ..., { cancelToken: source.token }).then...

And finally

componentWillUnmount = () => {
    source.cancel();
}

But I still get the warning. I've lost several hours trying to get rid of this, I'm losing precious time, and nothing seems to work.

Also, for whatever reason, if I remove the addUser function, I lose the warning, but it makes no sense, considering that is just a Redux dispatch, and as far as I know, they are supposed to be synchronous and have nothing to do with the local state of the component.

What could be the issue?

CodePudding user response:

You could try:

axios.post('/signin', { email: inputs.email, password: inputs.password })
.then(response => {
  localStorage.setItem('token', JSON.stringify(response.data.token));
  addUser({ id: response.data.id, name: response.data.username }); 
  return <Redirect to='/'/>;
})
.catch(err => setLastError(err.response.data));
  • Related