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

Firestore获取单个文档报错:无法读取未定义的属性

问题分析与解决方案

主要问题及修复步骤

1. 变量遮蔽+未提取文档数据

在 useProfile.ts 的 onSnapshot 回调中,参数名 profile 与外部的 profile ref 变量重名,导致赋值时错误地将 Firestore 的 DocumentSnapshot 对象而非实际文档数据赋值给了 ref。同时未调用 .data() 方法提取文档内容。

修复后的 useProfile.ts:

import { ref, watch } from 'vue'
import { useUserSession } from "/@src/stores/userSession";
import { Profile } from "/@src/types/profile";

import {
    getFirestore,
    onSnapshot,
    doc,
} from "firebase/firestore";
  
const db = getFirestore();
const userSession = useUserSession();

export const profile = ref<Profile>();

export const getProfile = (id: string) => {
    const unsub = onSnapshot(doc(db, "profiles", id), (docSnap) => {
        console.log("Profile Retrieved Successfully : ", docSnap.id, " => ", docSnap.data());
        // 提取文档数据并转换为 Profile 类型
        profile.value = docSnap.data() as Profile;
    });
    return unsub; // 返回取消订阅函数,避免内存泄漏
}

// 监听用户 uid 变化,确保登录后再获取数据
watch(() => userSession.uid, (newUid) => {
    if (newUid) {
        getProfile(newUid);
    }
}, { immediate: true });

2. 模板属性名拼写错误

test.vue 中使用了 profile.images.picture,但 Profile 类型定义的是 images.avatar,属性名不匹配导致无法读取。

3. 未处理数据加载前的 undefined 状态

组件初始化时 profile 为 undefined,直接访问其属性会触发 "Cannot read properties of undefined" 错误。

修复后的 test.vue:

<script setup lang="ts">
import { useViaPlaceholderError } from '/@src/composable/useViaPlaceholderError'
import { profile } from "/@src/composable/useProfiles";
</script>

<template>
  <!-- 使用 v-if 确保 profile 存在后再渲染 -->
  <div class="column is-one-fifth" v-if="profile">
    <img
        class="project-avatar"
        :src="profile.images.avatar"
        alt="用户头像"
        @error.once="(event) => useViaPlaceholderError(event, '150x150')"
      />
      <h3>{{ profile.personal.nameFirst }} {{ profile.personal.nameLast }}</h3>
      <p>{{ profile.professional.cluster }}</p>
      <progress class="progress is-primary is-tiny" value="31" max="100">
        31%
      </progress>
  </div>
</template>

额外优化建议

  • 组件卸载时调用 getProfile 返回的取消订阅函数,避免内存泄漏:
    import { onUnmounted } from 'vue'
    const unsub = getProfile(uid);
    onUnmounted(() => unsub());
    
  • 处理文档不存在的情况:
    if (docSnap.exists()) {
        profile.value = docSnap.data() as Profile;
    } else {
        console.log("Profile 文档不存在");
        // 可设置默认值或提示用户
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:40:26