简体   繁体   中英

Can't perform a react state update on an unmounted component after adding await tag to dispatch

I have added an await tag to a redux dispatch and now I receive this error:

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.
    in LoginForm (created by ConnectFunction)
    in ConnectFunction (at login.js:12)
    in div (at login.js:11)

Can someone please explain why this is occurring and how I can go about 'cleaning up'my asynchronous task? I don't understand which component has not been mounted

My code:

login.js:

import React, { Component } from 'react';
import LoginForm from '../components/form/loginForm';
import { connect } from 'react-redux';
import { SUCCESS, HOME } from '../common/webUtils';
import { Redirect } from 'react-router-dom';

class Login extends Component {
  render() {
    if( this.props.loginStatus === SUCCESS ) return <Redirect to = {HOME}/>
    else return (
      <div style = {{paddingTop: "180px", background: 'radial-gradient(circle, rgba(106,103,103,1) 0%, rgba(36,36,36,1) 100%)', height: "100vh"}}>
        <LoginForm/>
      </div>
    );
  }
}

function mapStateToProps( state ) {
  return {
    loginStatus: state.userReducer.loginStatus
  }
}

export default connect ( mapStateToProps ) ( Login );

Dispatch code that causes the warning from loginForm.js:

async function handleSubmit() {
    setSubmitted( true )
    if( isValidForm() ) {
      const details = {
          "username": userName,
          "password": password
      }
      await props.login( details )
      if( props.loginStatus !== SUCCESS ) handleShowError()
    } else { 
      handleShowError()
    }
  }

setShowError function and corresponding state value initialisation:

const [showError, setShowError] = React.useState( false )

const handleShowError = () => {
    setShowError( true )
  };

it seems the login is not get notified by "async function handleSubmit" result I believe this the reason the component is not get mounted.

In general, with redux, you need middleware such thunk or saga to manage the service workers in the background.

Redux alone cannot do this job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM