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

接收推送通知时报Cannot read property 'length' of undefined错误如何解决

问题排查与解决方案

错误根因

你遇到的Cannot read property 'length' of undefined报错定位在for (var i = response.length - 1; i >= 0; i--)这一行,核心原因有两点:

  • 后端fetch_notifications.php返回的JSON结构不符合预期:当response.status == 1时,返回值中不存在notifications字段、或字段名拼写不匹配、或该字段值不是数组类型,导致你把response重赋值为response.notifications后得到的是undefined,调用length属性就会抛出错误。
  • 代码无前置校验逻辑:拿到返回值后没有做合法性判断就直接访问属性,触发了运行时错误。

另外你的代码还存在一个隐藏的闭包问题:循环中用var声明url和noti变量,会导致所有通知的点击事件都只会触发最后一条通知的跳转逻辑,关闭的也是最后一条通知。

修复方案

1. 前端代码修复

在原逻辑基础上增加合法性校验,同时修复闭包问题,修复后代码如下:

setInterval(function() {
  check_notification();
}, 10000);

function check_notification() {
  var Uid = ReadCookie("Uid");
  if (Uid !== undefined) {
    $.ajax({
      url: "fetch_notifications.php?user_id=" + Uid,
      success: function(result) {
        // 增加JSON解析错误捕获,避免后端返回非JSON内容报错
        var response;
        try {
          response = JSON.parse(result);
        } catch (e) {
          console.log("通知接口返回非合法JSON:", e);
          return;
        }
        if (response.status == 1) {
          // 先校验notifications字段存在且为数组
          if (!Array.isArray(response.notifications)) {
            console.log("通知字段格式错误");
            return;
          }
          const notifications = response.notifications;
          // 用let声明循环变量,解决闭包问题
          for (let i = notifications.length - 1; i >= 0; i--) {
            const url = notifications[i]['url'];
            const noti = new Notification(notifications[i]['title'], {
              icon: 'logo.png',
              body: notifications[i]['body'],
            });
            noti.onclick = function() {
              window.open(url);
              noti.close();
            };
          };
        } else {
          console.log(response.error || "获取通知失败");
        }
      },
      // 增加请求失败的错误处理
      error: function(err) {
        console.log("通知接口请求失败:", err);
      }
    });
  }
}

2. 后端接口校验

检查fetch_notifications.php的返回逻辑:

  • 无论有没有新通知,只要status=1就必须返回notifications字段,没有通知时返回空数组[]即可,不能省略该字段
  • 确保返回的JSON结构正确,字段名和前端调用的notifications完全一致,大小写不要写错

内容的提问来源于stack exchange,提问作者Luna G.P.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 07:21:03