You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Novu新通知触发Mantine弹窗异常:refetch后notifications为空

问题原因及解决方案

核心原因

  • React的状态更新是异步的,调用refetch()触发数据重新获取后,当前函数闭包中的notifications还是旧的状态值,不会立刻更新为新数据,所以打印出来仍是空数组。
  • useNotifications的refetch方法仅负责触发重新请求,不会直接同步返回最新数据,你需要等待组件状态更新后才能拿到新的notifications。

解决办法

办法一:直接使用refetch的返回值

如果你的useNotifications钩子的refetch方法会返回最新的通知数据(类似React Query的refetch返回带data的对象),可以直接用返回值处理:

const handleNewNotification = async () => {
  const response = await refetch();
  // 假设response.data为最新通知列表,根据实际返回结构调整
  const newNotifications = response.data;
  console.log(newNotifications);
  newNotifications.forEach((n) => {
    showNotification({
      id: n._id,
      title: 'New Notification',
      message: `${n.content}`,
      autoClose: false,
      onClose: ({ id }) => {
        markAsSeen(id);
      }
    })
  })
}

办法二:监听notifications状态变化

通过useEffect监听notifications的变化,当状态更新后再触发弹窗逻辑:

// 提取弹窗逻辑为单独函数
const showNewNotifications = (notificationsList) => {
  notificationsList.forEach((n) => {
    showNotification({
      id: n._id,
      title: 'New Notification',
      message: `${n.content}`,
      autoClose: false,
      onClose: ({ id }) => {
        markAsSeen(id);
      }
    })
  })
}

// 仅负责触发重新获取数据
const handleNewNotification = async () => {
  await refetch();
}

// 监听notifications变化,有新数据时弹窗
useEffect(() => {
  if (notifications.length > 0) {
    showNewNotifications(notifications);
  }
}, [notifications])

办法三:利用Socket事件返回的数据直接处理

如果unseen_count_changed事件返回的data包含新增通知的信息,可以直接用这些数据弹窗,避免重复请求:

useEffect(() => {
  if (novuSocket) {
    novuSocket.on('unseen_count_changed', async (data) => {
      console.log(data);
      // 假设data.newNotifications是新增的通知列表,根据实际结构调整
      if (data.newNotifications?.length > 0) {
        data.newNotifications.forEach((n) => {
          showNotification({
            id: n._id,
            title: 'New Notification',
            message: `${n.content}`,
            autoClose: false,
            onClose: ({ id }) => {
              markAsSeen(id);
            }
          })
        })
      } else {
        await refetch();
      }
    });
  }

  return () => {
    if (novuSocket) {
      novuSocket.off('unseen_count_changed');
    }
  }
}, [novuSocket])

内容的提问来源于stack exchange,提问作者The Code Crusader

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 18:25:49