【问题标题】:Can't Perform a React State Update on an Unmounted Component. This is a no-op - Mob X Related无法对未安装的组件执行 React 状态更新。这是一个无操作 - Mob X 相关
【发布时间】:2019-09-26 09:17:51
【问题描述】:

我目前正在开发一款智能家居类应用程序并且是初学者,我正在使用mobX 设置活动房间名称。

我在“仪表板”组件中将它们设置为容器的标题。然后我想使用存储在里面的变量来过滤另一个名为“房间”的组件中的房间。如果我对房间名称进行硬编码,它可以工作,但是当我用实际变量替换房间名称时会引发一堆错误。

我已经尝试在 componentWillUnmount() 中声明内容,但到目前为止还没有成功。

这是我设置变量的地方

handleClick(e){
      
        this.props.roomStore.room = e.target.closest('.btn__toggle').querySelector('.btn__headline').innerHTML;
      }

这就是我要找房间的地方

loadRooms(){
  if(this.state.isLoaded){
    var locations = this.state.things.filter( function (e){
      return e.location == this.props.roomStore.room}); //<- this is the relevant variable
          const habitems = locations.map((i, key) => 
          <div className="btn__toggle" key={i.UID} type="submit">
          <div className="btn__headline">{i.label}</div>
          </div>
              )
              return habitems;
            }         
}

这是我渲染我的项目的地方:

render() {
   
        if(this.state.isLoaded){
          return (
            <div>
          <h1 id="h1">{this.props.roomStore.room}</h1>
          <div className="btn__wrapper">{this.loadRooms()}</div>
          </div>
          );
        }

我认为它可能不起作用,因为在您实际打开正确的组件之前,该变量已在另一个组件中设置,该组件在渲染中使用它,因此整个组件甚至在安装之前就已渲染。

但我可能错了。任何帮助将非常感激。 出现的错误有:

index.module.js:860 Uncaught TypeError: Cannot read property 'props' of undefined

组件出现上述错误

Uncaught (in promise) TypeError: Cannot read property 'props' of undefined

react-dom.development.js:506 警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请在 componentWillUnmount 方法中取消所有订阅和异步任务。

【问题讨论】:

    标签: javascript reactjs react-router mobx-react


    【解决方案1】:

    您遇到的问题是您的过滤函数无法访问this,导致错误Cannot read property 'props' of undefined。您可以预先使用destructuring assignment 从道具中过滤掉您的roomStore,然后使用它而不是访问this.props

    loadRooms() {
        const { roomStore } = this.props;
        if (this.state.isLoaded) {
            var locations = this.state.things.filter( function (e){
                return e.location == roomStore.room
            });
    
            /* ... */
        }
    }
    

    解构赋值语法是一种 JavaScript 表达式,可以将数组中的值或对象中的属性解包到不同的变量中。

    【讨论】:

      猜你喜欢
      • 2021-10-13
      • 2021-07-01
      • 2020-11-21
      • 2019-11-09
      • 2019-05-30
      • 2021-05-30
      相关资源
      最近更新 更多