消息通知云函数报TypeError: Cannot read property 'child' of undefined
云函数报错逐点排查与修正方案
核心报错原因定位
- API版本参数错配:代码使用Firebase Functions v1+的新版回调签名
onWrite((snapshot, context) => {}),但取值逻辑混用了v0.x旧版写法。v1版本中实时数据库onWrite的第一个入参为Change类型对象,不存在data属性,代码中snapshot.data.child(...)的写法会直接触发Cannot read properties of undefined错误 - 未定义变量引用:代码中获取接收方token的位置使用了
event.data.child('receiverToken').val(),当前回调上下文根本不存在event变量,运行时会直接抛出ReferenceError: event is not defined - 业务逻辑错位:代码已经通过数据库查询拿到了
/users/${receiverId}的快照,却注释掉了从该快照读取messaging_token的正确逻辑,转而调用不存在的event对象获取token,完全偏离了原有设计的业务流程 - 缺少边界状态判断:
onWrite触发器会响应消息的新增、修改、删除全量操作,若触发场景为删除消息,变更后的数据库快照为空,直接读取子节点值会触发空指针错误;若必填字段缺失,后续推送流程也会连锁报错
修正后的可运行代码
首先确认函数初始化的基础依赖,完整修正代码如下:
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.sendNotification = functions.database.ref('/messages/{userId}/{messageId}') .onWrite((change, context) => { // 获取消息变更后的快照,若消息已删除则直接终止流程 const afterSnapshot = change.after; if (!afterSnapshot.exists()) { console.log("消息已删除,跳过通知推送"); return null; } const receiverId = context.params.userId; console.log("receiverId: ", receiverId); // 从变更后的快照中读取消息属性 const senderId = afterSnapshot.child('senderUid').val(); const message = afterSnapshot.child('messageBody').val(); const messageId = context.params.messageId; console.log("senderId: ", senderId, "message: ", message, "messageId: ", messageId); // 校验必填字段,避免空值触发后续流程错误 if (!senderId || !message || !receiverId) { console.log("消息必填字段缺失,终止推送"); return null; } // 查询发送者的展示名称 return admin.database().ref(`/Renters/${senderId}`).once('value').then(senderSnap => { const senderName = senderSnap.child("houseName").val() || "租房用户"; console.log("senderName: ", senderName); // 查询接收方的设备推送token return admin.database().ref(`/users/${receiverId}`).once('value').then(receiverSnap => { const token = receiverSnap.child("messaging_token").val(); console.log("token: ", token); if (!token) { console.log("接收方无有效推送token,终止推送"); return null; } // 构建通知负载并发送 console.log("构建通知推送消息"); const payload = { data: { data_type: "direct_message", title: `New Message from ${senderName}`, message: message, message_id: messageId, } }; return admin.messaging().sendToDevice(token, payload) .then(response => { console.log("Successfully sent message:", response); return response.successCount; }) .catch(error => { console.log("Error sending message:", error); }); }); }); });
部署验证注意事项
- 本地代码修改完成后,需要通过
firebase deploy --functions sendNotification重新部署对应函数,旧版本的错误逻辑不会自动生效 - 部署前确认Firebase项目已开启Cloud Messaging权限,否则调用
admin.messaging()接口会触发权限类报错
内容的提问来源于stack exchange,提问作者nelsola
相关产品推荐
相关产品推荐

