无法在尚未挂载的组件上调用 setState,即使它已经挂载?

Can't call setState on a component that is not yet mounted, even though it is?

提问人:TraktorJack 提问时间:10/23/2021 更新时间:10/23/2021 访问量:2497

问:

你们已经看到了错误,state = {};Warning: 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 class property with the desired state in the ImageTableItemComponent component.

我看到过类似的问题,但没有对我有帮助的答案。这是我的构造函数:

export default class ImageTableItemComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data : [], // ****** This one's the problem *****
            collapsible : false,
        }
        this.loadImagesWithTags();
    }

这是函数,我使用:loadImagesWithTags()setState

loadImagesWithTags() {
        const imagesAndTags = new ImagesAndTags();
        imagesAndTags.getImagesWithTags()
            .then(imagesAndTags => {
                const data = this.convertDataToObject(imagesAndTags)
                this.setState({data: data,})  // ****** Here I use setState *****
            })
            .catch(reason => {
                console.error('Error loading tags:', reason)
            });
    }

我以前使用过相同的方法,没有收到任何错误。是否存在错误或过时的依赖项或其他东西,我在这里没有看到的任何内容都会触发此错误?我已经删除了与我的代码有关的任何内容,所以我知道错误与数据有关。任何帮助都是值得赞赏的。collapsible: false,

reactjs setstate

评论


答:

2赞 silencedogood 10/23/2021 #1

不应在构造函数中调用在异步操作后分配状态的方法。相反,请在componentDidMount()

componentDidMount() {
    this.loadImagesWithTags();
}

我认为这个错误误导了你。这并不是说组件没有挂载,而是你在 React 组件生命周期中的错误时刻执行了状态更新。