【问题标题】:Can't call setState on a component that is not yet mounted, even though it is?不能在尚未安装的组件上调用 setState,即使它是?
【发布时间】:2021-10-22 17:02:35
【问题描述】:

你们已经看到错误了,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 astate = {}; 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


    【解决方案1】:

    您不应该在构造函数中的异步操作之后调用分配状态的方法。而是运行componentDidMount()中的方法

    componentDidMount() {
        this.loadImagesWithTags();
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-15
      • 1970-01-01
      • 2021-07-21
      相关资源
      最近更新 更多