Firebase云函数设备推送报错:Cannot read property 'user_id' of undefined
解决Firebase Cloud Functions中TypeError: Cannot read property 'user_id' of undefined的问题
嘿,这个问题我之前踩过坑!根源在于Firebase Cloud Functions的版本更新带来了参数结构的变化,你的代码还在用旧版本的写法~
问题原因
在Firebase Functions v1.0及以后的版本中,onWrite触发器的回调函数参数发生了变更:
- 旧版本:只接收一个
event对象,路径参数通过event.params获取 - 新版本:拆分为两个参数——
snapshot(数据快照)和context(上下文对象),路径参数需要从context.params里获取
你的代码还在使用event.params,但新版本里event已经不存在了,所以才会抛出“无法读取undefined的user_id属性”的错误。
修正后的代码
把你的函数改成下面这样就可以正常运行了:
exports.sendNotification = functions.database.ref('/messages/{user_id}/{rec_user_id}').onWrite((snapshot, context) => { const sender_user_id = context.params.user_id; const receiver_user_id = context.params.rec_user_id; console.log('We have a notification from : '+ sender_user_id+ " | Received by " + receiver_user_id); return; });
额外提示
- 可以检查一下你项目中
package.json里的firebase-functions版本号,如果是低于v1.0的旧版本,建议升级到最新稳定版,避免后续遇到更多兼容性问题 - 如果暂时不想升级版本,也可以继续使用旧写法,但需要确保你的
firebase-functions版本保持在v0.x系列,不过不推荐这种方式,因为旧版本不再接收功能更新和安全补丁啦
内容的提问来源于stack exchange,提问作者Nabeel Nazir
相关产品推荐
相关产品推荐

