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

求助:修复FieldValue.arrayUnion is not a function错误

解决FieldValue.arrayUnion is not a function错误

调用FieldValue.arrayUnion()时触发FieldValue.arrayUnion is not a function错误,错误出现在好友请求功能的对应代码行,多次更新npm版本、修改Firestore字段均未解决,详情如下:

相关代码

try {
    const recipientDocRef = doc(db, 'usersNew', selectedFriend.username);

    await updateDoc(recipientDocRef, {
        friendRequests: FieldValue.arrayUnion(user.uid)
    });

    toast.success(`Friend request sent to ${selectedFriend.username}`);
} catch (error) {
    console.error('Error sending friend request:', error);

    // More specific error messages (if possible)
    if (error.code === 'firestore/permission-denied') {} else {
        toast.error('You do not have permission to send friend requests. Please check your Firestore rules.');
    }
    toast.error('Error sending friend request. Please try again.');
} finally {
    setIsLoadingRequest(false);
}

FieldValue导入方式

import { FieldValue } from 'firebase/firestore'; 

已尝试的操作

  • 多次更新npm版本
  • 修改Firestore数据库字段

解决方案

1. 统一Firebase依赖版本

检查package.json中firebase及相关子包(如@firebase/firestore)的版本是否一致,版本混用会导致API不兼容。执行以下命令更新到最新统一版本:

npm install firebase@latest --save

2. 验证FieldValue的有效性

在调用arrayUnion前添加调试代码,确认FieldValue对象的结构:

console.log(FieldValue);

若输出结果中没有arrayUnion方法或FieldValue为undefined,说明导入异常,需检查版本或导入路径是否正确。

3. 确认Firestore实例初始化正确

确保db实例通过模块化SDK正确初始化:

import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';

const firebaseConfig = { /* 你的Firebase配置 */ };
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

错误的初始化会导致后续API调用失效。

4. 清理依赖缓存并重装

npm缓存可能导致版本不一致,执行以下命令清理后重新安装:

rm -rf node_modules package-lock.json
npm install

5. 匹配Firestore字段类型

确保usersNew集合中的friendRequests字段为数组类型,若字段为其他类型(如字符串、对象),需在Firebase控制台手动修改为数组类型后再调用arrayUnion。

内容的提问来源于stack exchange,提问作者Sai Monish Tunguturu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 02:06:15