首页 > 解决方案 > 无法在反应中设置未安装组件的状态

问题描述

我是 react 和 redux 的新手。这是,我在做什么:

我有一个组件,就像

class LandingPage extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      isloading: true
    }
  }

  componentDidMount() {
    this.props.fetchJobDescription().then(() => {
      this.setState({
        isloading: false
      })
    });
  }

render() {
    if (this.state.isloading) {
      return null;
    }
    else if (this.props.jobs && this.props.jobs.content && this.props.jobs.content.length > 0) {
      return <JobList />;
    }
    else if (this.props.isError) {
      return <ErrorComponent />
    }
    else {
      return <Redirect to="/create-job" />
    }
  }
}

动作就像,

export function fetchUserJd() {
  return (dispatch) => {
    let url = FETCH_JD_ROOT_URL + page + "&" + size;
    dispatch({
      type: REQUEST_INITIATED
    })
    return get(url)
      .then((response) => {
        if (response.status === 200) {
          dispatch({
            type: FETCHING_JOBDESCRIPTION_SUCCESS,
            data: response.payload
          })
          dispatch({
            type: REQUEST_SUCCESSED
          })
        } else {
          if (!response.status) {
            toastr.error('Our server is down. Please check again');
          }
          else if (response.status.status === 401) {
            dispatch(logout());
          }
          else if (response.status.status === 500) {
            toastr.error("Error while Fetching the job description,Please try again");
            dispatch({
              type: FETCHING_JOBDESCRIPTION_SUCCESS,
              data: response.status,
            });
            dispatch({
              type: REQUEST_SUCCESSED
            })
          } else {
            dispatch({
              type: REQUEST_SUCCESSED
            })
          }
        }
      })
    return Promise.resolve();
  }
};

现在,我的注销是,

export function logout() {
    console.log("calling the logout action");
    localStorage.clear();
    history.push('/login');
    return {
        type: LOGOUT_REQUEST
    }
}

class Header extends React.Component {

  constructor(props) {
    super(props);
  }

  logout = (e) => {
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
    e.preventDefault();
    this.props.logout();
  }


  render() {
    return (
      <Fragment>
        <Navigation
          isAuthenticated={localStorage.getItem("access_token") ? true : false}
          operationType={this.props.operationType}
          logout={this.logout} />
      </Fragment>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    isAuthenticated: state.LoginReducer.isAuthenticated,
    operationType: state.Header.operationType,
  }
}

在这里,当有一个无效的令牌时,比如在获取它时给我 401 未授权,然后我重定向用于注销操作。现在,

当我这样做时,我得到一个错误:

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 the componentWillUnmount method.
    in LandingPage (created by Context.Consumer)
    in Connect(LandingPage) (created by Route)

我该如何解决这个错误?

标签: reactjsreduxreact-redux

解决方案


这是您的代码中发生的一个小问题。当您收到 401 令牌时,您尝试使用 history.push 从操作创建者中重定向到注销,这将卸载您的 LandingPage 组件,但同时您正在尝试setStatewith loading: false,因此您会收到此警告。解决方法很简单

class LandingPage extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      isloading: true
    }
    this._mounted = true;
  }

  componentDidMount() {
    this.props.fetchJobDescription().then(() => {
      if (this_mounted) {
         this.setState({
           isloading: false
         }) 
      }
    });
  }

  componentWillUnmount() {
     this._mounted = false;
  }
render() {
    if (this.state.isloading) {
      return null;
    }
    else if (this.props.jobs && this.props.jobs.content && this.props.jobs.content.length > 0) {
      return <JobList />;
    }
    else if (this.props.isError) {
      return <ErrorComponent />
    }
    else {
      return <Redirect to="/create-job" />
    }
  }
}

否则在动作创建者中,您可以抛出错误而不是调度注销动作,并在调度.catch块中fetchJobDescription注销注销动作

在登陆页面中

this.props.fetchJobDescription().then(() => {
       this.setState({
           isloading: false
       }) 
    }).catch((err) => {
        this.props.logout();
    });

并在行动创造者

  else if (response.status.status === 401) {
        throw new Error('Error in status')
  }

推荐阅读