You need to enable JavaScript to run this app. Firebase通过transaction修改通知seen布尔值时报_delegate未定义错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Firebase通过transaction修改通知seen布尔值时报_delegate未定义错误如何解决

报错原因
  • 错误由const doc = notificationDoc.get();这行代码触发。Firestore 的 DocumentSnapshot 实例的get()方法必须传入目标字段名作为参数才能返回对应值,无参数调用时会返回undefined。后续你尝试读取undefined.user属性时,就触发了Firebase底层预构建代码中的_delegate属性读取报错。
  • 你需要获取完整的文档数据,应该调用data()方法,而不是无参的get()方法。
修复方案

修改后的代码如下,核心调整是将无参get()替换为data(),同时放开更新逻辑将seen设为目标值true:

const markNotificationsAsSeen = () => {
    const notificationDocRef = db
        .collection("notifications")
        .doc("Ddo1Z3GtgwzytZig1GPD");

    return db
        .runTransaction((transaction) => {
            return transaction.get(notificationDocRef).then((notificationDoc) => {
                if (!notificationDoc.exists) {
                    throw "Document does not exist!";
                }
                // 替换为data()获取完整文档数据
                const doc = notificationDoc.data();
                if (
                    doc.user.askerUserId === auth.currentUser.uid &&
                    doc.seen === false
                ) {
                    transaction.update(notificationDocRef, { seen: true });
                    console.log("I passed");
                }
            });
        })
        .then(() => {
            console.log("Transaction successfully committed!");
        })
        .catch((error) => {
            console.log("Transaction failed: ", error);
        });
};

如果你的业务逻辑不需要先读取文档内容做校验、直接更新即可,也可以不用Transaction,直接调用单文档更新方法,代码更精简:

const markNotificationsAsSeen = () => {
    const notificationDocRef = db.collection("notifications").doc("Ddo1Z3GtgwzytZig1GPD");
    return notificationDocRef.update({ seen: true })
        .then(() => console.log("更新成功"))
        .catch(err => console.log("更新失败", err));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 03:45:04