相关疑难解决方法(0)

在已卸载的组件中发出有关setState的警告

我收到这个错误:

warning.js:33警告:无法在卸载的组件上调用setState(或forceUpdate).这是一个无操作,但它表示应用程序中存在内存泄漏.要修复,请取消componentWillUnmount方法中的所有订阅和异步任务.

但我没有使用componentWillUnMount方法.

我正在使用HOC来确保用户在访问其/ account帐户之前已通过身份验证.

这是路线:

<StyleRoute props={this.props} path="/account" component= 
{RequireAuth(Account)} />
Run Code Online (Sandbox Code Playgroud)

其中RequireAuth是HOC.这是HOC:

 import { withRouter } from 'react-router';

export default function RequireAuth(Component) {

  return class AuthenticatedComponent extends React.Component {

    componentWillMount() {
      this.checkAuth();
    }

    checkAuth() {
      if ( ! this.props.isAuthenticated) {
        this.props.history.push(`/`);
      }
    }

    render() {
      return this.props.isAuthenticated
        ? <Component { ...this.props } />
        : null;
    }

  }

  return withRouter(AuthenticatedComponent);
}
Run Code Online (Sandbox Code Playgroud)

代码按预期工作,但是在呈现/ account时我收到了错误.正如您所注意到的,我的直接代码中没有任何地方存在componentWillUnMount方法.我真的不知道为什么这个警告不断出现,任何信息都会有所帮助.


更新5/23/18:

为了摆脱这个错误并且仍然有道具传递,我做了两件事:

1)我选择在父App组件中使用两个更高阶的函数,而不是使用HOC.一个高阶函数用于传递道具,另一个用于检查身份验证.我无法传递除浏览器历史之外的任何道具,因此下面是renderProps函数.

renderProps = (Component, props) => {
  return (
      <Component {...props} />
    );
}

checkAuth …
Run Code Online (Sandbox Code Playgroud)

reactjs

29
推荐指数
2
解决办法
3万
查看次数

标签 统计

reactjs ×1