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

Firebase Functions报错:无法读取undefined的'user_id'属性

解决Firebase Functions读取user_id时的undefined错误

嘿,这个问题我之前刚踩过坑!你碰到的无法读取undefined的'user_id'属性错误,核心原因是你用了Firebase Functions旧版本的语法,而当前函数运行时的参数结构已经更新了。

问题根源

在Firebase Functions的早期版本中,onWrite的回调只接收一个event对象,路径参数(比如你的{user_id})确实挂载在event.params上。但后来的版本(从Cloud Functions for Firebase v1.0.0开始),onWrite的回调参数做了拆分:

  • 第一个参数change:包含数据写入前后的快照(before和after)
  • 第二个参数context:包含路径参数、认证信息等上下文数据,路径参数现在在context.params里

修正后的代码

把你的代码改成下面这样就能正常运行了:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

// 新版不需要手动传入functions.config().firebase,自动加载默认配置
admin.initializeApp();

exports.sendNotification = functions.database.ref('/notifications/{user_id}').onWrite((change, context) => {
  // 从context.params里获取user_id
  console.log('Testing stuff', context.params.user_id);
  // 建议返回一个Promise确保函数正常结束(空函数也可以return; 但返回Promise更规范)
  return Promise.resolve();
});

额外小提示

  • 新版的admin.initializeApp()不需要再传递functions.config().firebase参数,Firebase会自动识别当前项目的配置,简化了初始化步骤。
  • 如果你的函数需要处理数据变化逻辑,可以通过change.before和change.after获取写入前后的数据快照。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:36:21