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

Firebase JS出现TypeError: doc is not a function报错求排查

报错根因

出现Uncaught (in promise) TypeError: doc is not a function是典型的变量名遮蔽冲突:

  • 你已经从Firebase Firestore SDK中导入了用于构造文档引用的doc()函数
  • 但在getDocs结果的forEach遍历回调中,你将单条文档快照的形参也命名为了doc
  • 回调函数内部作用域优先级更高,此时doc指向的是文档快照对象(不是导入的函数),执行doc(...)调用时自然会报不是函数的错误。
修复方案

将forEach回调的文档快照参数重命名,避开和导入的doc函数重名即可,比如改为docSnap。
修复后的完整可运行参考代码:

// 记得补上缺失的initializeApp导入
import { initializeApp } from "firebase/app";
import {
  getFirestore,
  addDoc,
  doc,
  updateDoc,
  collection,
  query,
  where,
  getDocs,
  setDoc,
} from "firebase/firestore";

const app = initializeApp(firebaseConfig);
const firestore = getFirestore(app);

var files = [....]

getDocs(collection(firestore, "property")).then((querySnapshot) => {
  // 形参改名为docSnap,不再和上层的doc函数冲突
  querySnapshot.forEach((docSnap) => {
    const currentFileno = decrypt(docSnap.data().fileno);
    if (files.includes(currentFileno)) {
      const owner = files.indexOf(currentFileno) === 6 ? "ABC" : "XYZ";
      const bref = doc(collection(firestore, "property"), docSnap.id);
      updateDoc(bref, { owner: encrypt(owner) }).then(() => {
        console.log("updated")
      })
    }
  });
});
额外提示
  • 原代码缺失initializeApp的导入语句,直接运行会报initializeApp is not defined,需要从firebase/app包补导入
  • 原代码中files.includes(decrypt(doc.data().fileno), 6)写法不符合预期:Array.includes()的第二个参数是搜索的起始索引,不是要匹配的位置,如果要判断文件序号在数组第6位,需要用indexOf判断返回值是否等于6

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 21:06:27