gpt4 book ai didi

javascript - 无法在尚未安装的组件上调用 setState

转载 作者:可可西里 更新时间:2023-11-01 01:43:53 24 4
gpt4 key购买 nike

这是我第一次遇到这种警告信息。

Can't call setState on a component that is not yet mounted.

跟随:

This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state directly or define a state = {}; class property with the desired state in the MyComponent component.

尚未安装”部分实际上几乎没有意义,因为触发问题的唯一方法是通过单击组件中的按钮来调用函数需要安装才能看到按钮。该组件在任何给定时间都不会卸载。

这个虚拟组件在我的应用程序中重现了错误:

import PropTypes from 'prop-types'
import React from 'react'

export default class MyComponent extends React.Component {
constructor (props) {
super(props)
this.state = {
initial: 'state'
}
this.clickMe = this.clickMe.bind(this)
}

clickMe () {
this.setState({
some: 'new state'
})
}

render () {
return (
<div>
<button onClick={this.clickMe}>click</button>
</div>
)
}
}

我正在使用:

"react": "16.3.2",
"react-dom": "16.3.2",
"mobx": "4.2.0",
"mobx-react": "5.1.2",

我是否遗漏了最新版本的 React/mobx 中的某些内容? (注意该组件不使用任何与 mobx 相关的东西,但它的父级是一个 mobx-react 观察者)

编辑:

肯定有一些与组件实例相关的东西,进一步的调查表明,在某些情况下,在渲染函数中创建一个处理程序会使这个警告消失,但并非在所有情况下都是如此。

class MyComponent extends React.component {
constructor (props) {
// ...
this.clickMeBound = this.clickMe.bind(this)
}

clickMe () {
...
}

render () {
// works
<button onClick={() => {this.clickMe()}}>click arrow in render</button>

// warning: Can't call setState on a component that is not yet mounted.
<button onClick={this.clickMeBound}>click bound</button>
}
}

编辑 2:

我已经从我的 Webpack 配置中的条目中删除了“react-hot-loader/patch”,并且像这样的一些奇怪的问题已经消失了。我没有把它作为答案,因为错误消息本身仍然很奇怪,这会在控制台中引起警告。不过一切正常。

最佳答案

您收到此警告是因为您在构造函数中设置了对 clickMe 方法 的引用,然后该构造函数使用了 setState()

constructor (props) {
super(props)
this.state = {
initial: 'state',
some: ''
}
this.clickMe = this.clickMe.bind(this); <--- This method
}

clickMe () {
this.setState({
some: 'new state' <-- the setState reference that is causing the issue
})
}

尝试从构造函数中删除 this.clickMe = this.clickMe.bind(this) 并在生命周期方法中执行此操作,例如 componentWillMount() 或 ComponentDidMount()。对于 React 16 及更高版本,您可以使用带有 "SAFE_" 前缀的 componentWillMount 方法[SAFE_componentWillMount]

 componentWillMount() {
this.clickMe = this.clickMe.bind(this);
}

clickMe () {
this.setState({
some: 'new state'
})
}

关于javascript - 无法在尚未安装的组件上调用 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50162522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com