【问题标题】:React mqtt subscription setState warningReact mqtt 订阅 setState 警告
【发布时间】:2015-10-15 20:09:59
【问题描述】:

我将 https://www.npmjs.com/package/mqtt 与 React 一起使用。在我的组件中,我有:

componentDidMount:function(){

        client.subscribe('test/topic');
        client.on('message',function(topic,message){

            if(topic==='test/topic'){
                console.log(message.toString());
                this.setState({value:parseInt(message.toString())});


            }
        }.bind(this));

    },
componentWillUnmount:function(){
        client.unsubscribe('test/topic');
    },

所以我在组件挂载时订阅主题,在组件卸载时取消订阅。但是,当我转到我的应用程序中的另一个视图并返回时,每条 mqtt 消息都会收到警告:

Warning: setState(...): Can only update a mounted or mounting component.
This usually means you called setState() on an unmounted component.
This is a no-op.

我做错了什么?

【问题讨论】:

    标签: javascript reactjs mqtt


    【解决方案1】:

    我曾经有过类似的问题。从那以后,我已经为我的套接字侦听器移回了旧的useEffect 语法,现在我似乎没有收到这些警告。不确定这是否是解决方法,但希望对您有所帮助!

    useEffect(() => {
        client.on('message' () => {
            // update state
        }
        client.on('disconnect', () => {
            // update state
        }
    })
    

    【讨论】:

    • 对不起 - 我刚刚注意到这个问题的年龄!可能不再相关,但无论如何希望它有所帮助。
    【解决方案2】:

    回调函数在声明 didMount 方法时被调用。将回调移动到它自己的方法中。你也不需要绑定this

    【讨论】:

    • 没有帮助。我将所有类重构为 ES6,将回调移到它自己的函数中,但我仍然收到此警告。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多