简体   繁体   English

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

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

I am getting this warning every time I sign in, 我每次登录时都会收到此警告,

Warning: Can't call setState (or forceUpdate) on an unmounted component. 警告:无法在卸载的组件上调用setState(或forceUpdate)。 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. 要修复,请取消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 withRouter so 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 index.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?

It's async so 这是异步的

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

make error You can use this._mount to 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:""
})
...

You can use _isMount with overloading the setState function: 您可以使用_isMount重载setState函数:

componentWillUnmount() {
    this._isMount = false;
}

componentDidMount() {
    this._isMount = true;
}

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

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 async and 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();
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 反应警告:无法在未安装的组件上调用 setState(或 forceUpdate) - React Warning: Can't call setState (or forceUpdate) on an unmounted component 警告:无法在React Native中的已卸载组件上调用setState(或forceUpdate) - Warning: Can't call setState (or forceUpdate) on an unmounted component in React Native 反应-警告:无法在未安装的组件上调用setState(或forceUpdate) - React - Warning: Can't call setState (or forceUpdate) on an unmounted component 无法在卸载的组件上调用setState(或forceUpdate) - Can't call setState (or forceUpdate) on an unmounted component 如何解决:无法在 React-Native 中的未挂载组件警告上调用 setState(或 forceUpdate)? - How to solve: Can't call setState(or forceUpdate) on an unmounted component warning in React-Native? 如何修复“index.js:1446 警告:无法在未安装的组件上调用 setState(或 forceUpdate)...”在 ReactJS 中 - How to fix 'index.js:1446 Warning: Can't call setState (or forceUpdate) on an unmounted component..." in ReactJS 无法在已卸载的组件上调用setState(或forceUpdate)。 应对 - Can't call setState (or forceUpdate) on an unmounted component. React 无法使用componentDidMount从API提取数据:无法在已卸载的组件上调用setState(或forceUpdate) - Cannot fetch data from an API using componentDidMount: Can't call setState (or forceUpdate) on an unmounted component 无法在已卸载的组件上调用setState(或forceUpdate)。 react-image-gallery上的内存泄漏 - Can't call setState (or forceUpdate) on an unmounted component. Memory leak on react-image-gallery 有人知道如何解决此错误:无法在已卸载的组件上调用setState(或forceUpdate)吗? - Does somebody know how to fix this error: Can't call setState (or forceUpdate) on an unmounted component…?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM