【问题标题】:Firebase Functions - sending pushes and got an error saying "TypeError: Cannot convert undefined or null to object" [closed]Firebase 函数 - 发送推送并收到错误消息“TypeError:无法将未定义或 null 转换为对象”[关闭]
【发布时间】:2020-10-19 22:38:00
【问题描述】:

我正在使用 FCM 和 Firebase 函数向用户发送推送通知,但遇到了问题。我收到一条错误消息“TypeError:无法将未定义或 null 转换为对象”,并认为这是由以下一行引起的:

const tokens = Object.keys(afterData.fcm_tokens)

但是,当将其打印到控制台时,它的值似乎是数组形式,因此标记不会为空:

sendPush
[ 'my_long_fcm_token01', 'my_long_fcm_token02', 'my_long_fcm_token03' ]

以下是完整的错误描述:

TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at exports.sendPush.functions.database.ref.onWrite (/srv/index.js:57:27)
    at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:134:23)
    at /worker/worker.js:825:24
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7) 

这是我的推送功能:

exports.sendPush = functions.database.ref('/user_pushes/{uid}').onWrite((change, context) => {

    const afterData = change.after.val();
    const tokens = Object.keys(afterData.fcm_tokens)
    console.log(tokens)

    const payload = {
        notification: {
            uid: afterData.sender_uid,
            title: afterData.sender_name,
            subtitle: afterData.roomId, // I need this property as room id
            body: afterData.message,
            badge: '1',
            sound: 'default',
            mutable_content: 'true',
        },
        data: {
              image_url: afterData.image_url
        }
    };
    return admin.messaging().sendToDevice(tokens, payload);
});

编辑:根据建议,我将问题编辑为 1 以便更专注。

【问题讨论】:

  • 您的 change.after.val() 函数显然返回 null。
  • 感谢罗伯特·哈维的建议。我是 Javascript 新手,您能具体说明一下应该如何修复它吗?
  • 我首先要弄清楚该函数的作用,以及它返回 null 的原因。
  • 在 Stack Overflow 上,请将每个帖子限制在一个问题或问题上。否则,它可能会因为“需要关注”而关闭。

标签: javascript firebase push-notification google-cloud-functions firebase-cloud-messaging


【解决方案1】:

感谢 Robert Harvey 的回复,我通过深入研究 change.after.val() 找到了导致此错误的原因。我没有意识到这会返回 nil,因为我认为它不应该,但实际上这是因为我出于目的立即更新和删除了节点。由于删除了节点,我认为对象返回 nil 并且发生了错误。

当我使用onWrite() 时,节点被意外触发了两次,因此我将onWrite() 更改为onUpdate,现在它可以正常工作了。有关更多详细信息,请查看 Doug Stevensons 的精彩解释:

Value of firebase functions onwrite sometimes is null

【讨论】:

    猜你喜欢
    • 2020-12-22
    • 2021-12-12
    • 2021-01-23
    • 2022-10-18
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    相关资源
    最近更新 更多