javascript 警告:无法在未挂载的组件上调用 setState(或 forceUpdate)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50504195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:08:53  来源:igfitidea点击:

Warning: Can't call setState (or forceUpdate) on an unmounted component

javascriptreactjsreact-router

提问by tony chen

I am getting this warning every time I sign in,

每次登录时都会收到此警告,

Warning: Can't call setState (or forceUpdate) 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.

警告:无法在未安装的组件上调用 setState(或 forceUpdate)。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请取消 componentWillUnmount 方法中的所有订阅和异步任务。

Here is my code:

这是我的代码:

authpage.js

authpage.js

 handleLoginSubmit = (e) => {
    e.preventDefault()
    let { email,password } = this.state
    const data = {
      email : email,
      password : password
    }
    fetch('http://localhost:3001/auth/login',{
      method : 'post',
      body : JSON.stringify(data),
      headers : {
        "Content-Type":"application/json"
      }
    }).then(res => res.json())
    .then(data => {
      if(data.success){
        sessionStorage.setItem('userid',data.user.id)
        sessionStorage.setItem('email',data.user.email)
      }
      this.setState({loginData : data,
                     userData : data,
                     email:"",
                     password:""})
      if(data.token) {
        Auth.authenticateUser(data.token)
        this.props.history.push('/dashboard')
      }
      this.handleLoginMessage()
      this.isUserAuthenticated()
    })
  }

export default withRouter(AuthPage)

use withRouterso I can access props which I use to navigate this.props.history.push('/dashboard')if I didn't use withRouter I cannot access this.props

使用withRouter这样我就可以访问我用来导航的道具,this.props.history.push('/dashboard')如果我没有使用 withRouter 我无法访问 this.props

index.js

索引.js

const PrivateRoute = ({ component : Component, ...rest }) => {
  return (
    <Route {...rest} render = { props => (
    Auth.isUserAuthenticated() ? (
      <Component {...props} {...rest} />
    ) : (
      <Redirect to = {{
        pathname: '/',
        state: { from: props.location }
      }}/>
    )
  )}/>
  )
}

const PropsRoute = ({ component : Component, ...rest }) => (
  <Route {...rest} render = { props => (
    <Component {...props} {...rest} />
  )}/>
)

const Root = () => (
  <BrowserRouter>
    <Switch>
      <PropsRoute exact path = "/" component = { AuthPage } />
      <PrivateRoute path = "/dashboard" component = { DashboardPage } />
      <Route path = "/logout" component = { LogoutFunction } />
      <Route component = { () => <h1> Page Not Found </h1> } />
    </Switch>
  </BrowserRouter>
)

I think the problem is with my withRouter, how can we access this.props without using withRouter ?

我认为问题出在我的 withRouter 上,我们如何在不使用 withRouter 的情况下访问 this.props ?

回答by nguyen nani

It's async so

这是异步的

this.setState({
   loginData : data,
   userData : data,
   email:"",
   password:""
})

make error You can use this._mountto check component is mounted or unmount

make error 可以使用this._mount来检查组件是挂载还是卸载

componentDidMount () {
   this._mounted = true
}
componentWillUnmount () {
   this._mounted = false
}
...
if(this._mounted) {
    this.setState({
        loginData : data,
        userData : data,
        email:"",
        password:""
})
...

回答by Ivan

You can use _isMountwith overloading the setStatefunction:

您可以使用_isMount重载setState函数:

componentWillUnmount() {
    this._isMount = false;
}

componentDidMount() {
    this._isMount = true;
}

setState(params) {
    if (this._isMount) {
        super.setState(params);
    }
}

回答by Thiago Marcello

I had some problems using this.setState({ any }).

我在使用时遇到了一些问题this.setState({ any })

Every time the component was built, it called a function that used Axios and the response made a this.setState({ any }).

每次构建组件时,它都会调用一个使用 Axios 的函数,然后响应生成一个this.setState({ any }).

My problem was solved as follows:

我的问题解决如下:

In the componentDidMount()function I call another function called initialize()that I left as asyncand through it I can call my function that performs fetch and this.setState({ any }).

componentDidMount()函数中,我调用了另一个被initialize()称为异步的函数,通过它我可以调用我的执行 fetch 和this.setState({ any }).

  componentDidMount() {
    this.initialize();
  }

  myFunction = async () => {
      const { data: any } = await AnyApi.fetchAny();
      this.setState({ any });
  }

  initialize = async () => {
    await this.myFunction();
  }