You need to enable JavaScript to run this app. React RabbitMQ监控调用含useDispatch的Notify报Invalid hook call问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

React RabbitMQ监控调用含useDispatch的Notify报Invalid hook call问题咨询

问题描述

尝试开发可监控RabbitMQ的后台工作组件,实现消息队列新增条目时在UI向用户推送通知,当前在AppBar组件中嵌套引入该后台工作组件,结构如下:

<AppBar>
    <BGWorker />
</AppBar>

现有实现代码

BGWorker.js 组件代码

import { Notify } from 'Notify.ts';
const { Client } = require('@stomp/stompjs');
class BGWorker extends Component {
    componentDidMount(){
        this.client = new Client();
        this.client.configure({
            brokerURL: 'ws://192.168.1.5:15555/ws',
            connectHeaders:{
                login: "guest",
                passcode: "guest"
            },
            onConnect: () => {
                this.client.suscribe('exchange/logs', message => {
                    console.log(message.body);       //控制台可正常打印出消息内容
                    Notify(message.body, 'info');    //调用该函数时触发报错
            },
        });
        this.client.activate();
    }
    render(){
        return (
            <div/>
        );
    }
}
export default BGWorker

Notify.ts 通知函数代码

import { useDispatch } from 'react-redux';
import { showNotification } from 'react-admin';
export const Notify = (msg:string, type:string='info') => {
    const dispatch = useDispatch();
    return () => {
        dispatch(showNotification(msg, type)); //调用React-Admin的showNotification方法推送通知
        //其余辅助逻辑
    };
};

遇到的报错

  • 消息接收阶段报错:每当接收到RabbitMQ推送的新条目消息时,抛出 Invalid hook call. Hooks can only be called inside the body of a functional component 错误。
  • 尝试自定义Hook方案修复失败:尝试实现自定义Hook接入逻辑,执行时抛出 Uncaught (in promise) TypeError: Cannot read property of 'subscribe' of undefined 错误,对应尝试的代码如下:
function useFoo(client){ 
    if(client !== undefined)
    {
        client.suscribe('exchange/logs', message => {
            Notify(message.body, 'info');
        },
    }
}

class BGWorker extends Component {
    ...
    onConnect: useFoo(this.client);
    ...
}

问题根因

  • Hook调用违规:useDispatch是React内置Hook,仅能在函数式组件的函数体顶层、或其他自定义Hook内部调用。原Notify是脱离React渲染上下文的普通工具函数,调用时会直接执行内部的useDispatch,返回的闭包函数从未被执行,本质上就是在普通非组件函数的执行流里触发了Hook调用,完全违反Hook调用规则,触发Invalid hook call报错。
  • 自定义Hook方案执行逻辑错误:代码中直接在类组件属性定义阶段同步执行onConnect: useFoo(this.client),此时this.client尚未完成初始化(值为undefined),且这种把Hook绑定在异步网络回调的写法不符合Hook的固定调用顺序要求。同时代码存在方法拼写错误:STOMP客户端的订阅方法正确名称为subscribe,原代码写为suscribe,也会触发方法不存在的报错。

修复方案

核心原则

所有React Hook必须在组件渲染周期内的固定位置调用,提前获取到dispatch方法的引用,将其传入异步消息回调中使用,绝对不能在脱离组件上下文的异步回调里调用Hook。

实现参考

函数式组件版本实现(推荐)

import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { showNotification } from 'react-admin';
import { Client } from '@stomp/stompjs';

const BGWorker = () => {
    // 在组件顶层调用Hook,拿到dispatch实例
    const dispatch = useDispatch();

    useEffect(() => {
        const client = new Client();
        client.configure({
            brokerURL: 'ws://192.168.1.5:15555/ws',
            connectHeaders: {
                login: "guest",
                passcode: "guest"
            },
            onConnect: () => {
                // 修正拼写错误
                client.subscribe('exchange/logs', message => {
                    // 直接使用提前获取的dispatch派发通知
                    dispatch(showNotification(message.body, 'info'));
                });
            },
        });
        client.activate();

        // 组件卸载时清理连接,避免内存泄漏
        return () => {
            client.deactivate();
        };
    }, [dispatch]);

    return null;
};

export default BGWorker;

原Notify.ts可简化为纯工具函数,移除Hook相关逻辑:

// Notify.ts
export const formatNotificationMsg = (rawMsg: string) => {
    // 原有辅助逻辑:消息格式化、内容过滤等
    return rawMsg.trim();
};

类组件版本实现(兼容原有类组件写法)

不需要使用Hook,通过Redux的connect高阶组件直接将dispatch注入到组件props中:

import { Component } from 'react';
import { connect } from 'react-redux';
import { showNotification } from 'react-admin';
import { Client } from '@stomp/stompjs';

class BGWorker extends Component {
    componentDidMount() {
        this.client = new Client();
        this.client.configure({
            brokerURL: 'ws://192.168.1.5:15555/ws',
            connectHeaders: {
                login: "guest",
                passcode: "guest"
            },
            onConnect: () => {
                this.client.subscribe('exchange/logs', message => {
                    // 直接使用props中注入的dispatch派发动作
                    this.props.dispatch(showNotification(message.body, 'info'));
                });
            },
        });
        this.client.activate();
    }

    componentWillUnmount() {
        this.client?.deactivate();
    }

    render() {
        return null;
    }
}

export default connect()(BGWorker);

内容的提问来源于stack exchange,提问作者Darren Ng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.24 07:06:08