React 表单提交和 "can't perform state update on an unmounted component"?

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

基本上,我有一个登录页面,当你填写表格并提交数据时,它会经过这个

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));
  }

它有效,但我收到警告

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.

所以我 google 这个问题,然后尝试添加 axios 取消令牌,更准确地说我设置

let source = axios.CancelToken.source();

然后将以下内容添加到我的 axios 请求中

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

最后

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

但我仍然收到警告。我花了几个小时试图摆脱这个,我正在浪费宝贵的时间,但似乎没有任何效果。

此外,无论出于何种原因,如果我删除 addUser 函数,我将失去警告,但考虑到这只是一个 Redux 调度,而且到目前为止,这没有任何意义据我所知,它们应该是同步的,与组件的本地状态无关。

可能是什么问题?

你可以试试:

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));