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

调用Firebase Firestore的getCountFromServer方法时抛出TypeError错误的原因排查求助

调用Firebase Firestore的getCountFromServer方法时抛出TypeError错误的原因排查求助

遇到这种按官方示例写代码却报错的情况确实挺闹心的,我先把你的问题梳理清楚,再一起排查可能的问题点:

你的代码片段:

import { getCountFromServer, getFirestore } from "firebase/firestore";

const db = getFirestore(env.CONFIG);

const q = query(collection(db, "entries"));

const snapshot = await getCountFromServer(q);

snapshot.data().count;

抛出的错误:

Index.esm2017.js:18650 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '_userDataWriter')
at data (index.esm2017.js:18650:1)

你的环境信息:

  • Firebase: 9.21.0
  • Node: 19.7.0
  • Typescript CRA (react-scripts): 5.0.1
  • 测试情况:不管用不用Firestore模拟器,都会出现相同错误

重点排查方向:

我觉得最有可能的问题出在Firestore实例的创建方式上,先看这个关键点:

在Firebase 9的模块化API中,getFirestore()的参数应该是已初始化的Firebase App实例,而不是直接传入配置对象!你的代码里直接把env.CONFIG传给了getFirestore,这是错误的用法。

正确的初始化流程应该是这样的:

import { initializeApp } from "firebase/app";
import { getCountFromServer, getFirestore, query, collection } from "firebase/firestore";

// 第一步:先初始化Firebase App
const app = initializeApp(env.CONFIG);
// 第二步:基于App实例创建Firestore实例
const db = getFirestore(app);

const q = query(collection(db, "entries"));
const snapshot = await getCountFromServer(q);
const count = snapshot.data().count;

因为如果直接传配置对象给getFirestore,它无法生成合法的Firestore实例,内部依赖的_userDataWriter就会是undefined,最终抛出你看到的那个TypeError。

其他次要排查点:

  • 确认query和collection方法也正确从firebase/firestore导入了(你的代码片段里没写这两个的导入,如果实际代码里也漏了,可能也会引发异常)
  • 可以尝试升级Firebase到最新稳定版,或者降级到9.20.0版本,排查是否是特定版本的兼容性问题
  • 检查你的env.CONFIG配置是否完整(apiKey、authDomain、projectId等必填字段是否都正确)

先试试修正Firebase App的初始化方式,应该能解决这个问题!

备注:内容来源于stack exchange,提问作者styke

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 16:04:29