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

使用Firebase JS SDK从Firestore获取数据时遇TypeError问题求助

问题分析与解决

核心错误原因

你代码里的await getDoc(doc(db, 'users', post.data.author)).data()写法有误。getDoc()返回的是一个Promise,直接在后面链式调用.data()时,你其实是在Promise对象上调用这个方法,而Promise本身并没有data()方法,这就是报错的根源。

修正后的代码

先通过await获取到实际的DocumentSnapshot对象,再调用它的data()方法,同时建议添加文档存在性检查,避免后续逻辑出错:

useEffect(() => {
    const getAuthorData = async () => {
        const docSnapshot = await getDoc(doc(db, 'users', post.data.author));
        if (docSnapshot.exists()) {
            setAuthorData(docSnapshot.data());
        } else {
            console.log("指定的用户文档不存在");
            // 可在此处理文档不存在的情况,比如设置默认值
        }
    };
    getAuthorData().catch(err => console.error("获取作者数据失败:", err));
}, [post.data.author]); // 添加依赖项,post变化时重新获取数据

额外检查点

  • 确认Firebase SDK导入正确(针对v9+模块化版本):
    你的导入应该类似这样:
    import { getDoc, doc } from "firebase/firestore";
    import { db } from "./your-firebase-config-file";
    
  • 验证post.data.author的值是否是Firestore中users集合下有效的文档ID,确保目标文档确实存在。
  • 检查组件的post依赖是否正确添加到useEffect的依赖数组中,避免闭包导致的旧值问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:20:41