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

Firebase运行报错firebase.apps.length of undefined及app.firestore()非函数问题

运行环境

  • 操作系统版本:Windows 11
  • 浏览器版本:Chrome
  • Firebase SDK版本:9.0.2
  • Firebase产品:database

问题原因

两个报错均由Firebase 9.x版本的API变更导致,该版本采用全新模块化设计,不再兼容8.x及更早版本的命名空间调用逻辑:

  • firebase.apps.length of undefined:v9已移除firebase.apps属性,需调用getApps()方法获取已初始化的应用实例列表
  • app.firestore() is not a function:v9不再在应用实例上挂载Firestore实例,需通过专门的getFirestore()方法获取实例

修复方案

方案1:使用官方推荐的模块化写法(推荐)

直接适配v9的模块化API,性能更优,支持tree shaking减小打包体积:

import { initializeApp, getApps, getApp } from 'firebase/app'
import { getFirestore } from 'firebase/firestore'
import { getAuth } from 'firebase/auth'

// 应用初始化逻辑
const app = !getApps().length ? initializeApp(firebaseConfig) : getApp()
// 获取Firestore实例
const db = getFirestore(app)
// 若需使用Auth能力可对应获取实例
const auth = getAuth(app)

方案2:使用兼容包过渡(不推荐长期使用)

如果原有代码量大不想一次性修改,可使用官方提供的兼容包保留旧版写法,兼容包后续会被废弃:

import * as firebase from 'firebase/app/compat'
import 'firebase/firestore/compat'
import 'firebase/auth/compat'

// 原有逻辑无需修改即可正常运行
const app = !firebase.apps.length ? firebase.initializeApp(firebaseConfig) : firebase.app()
const db = app.firestore()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:51:01