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

无法写入Firestore求排查方向:Storage与Realtime Database正常

问题:Firestore写入无响应,Storage与Realtime Database正常工作

点击按钮调用CheckoutForm时,控制台仅输出object 1,try/catch块之后的代码完全不执行,既无成功日志也无错误信息。相关代码如下:

firebase.js

import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
  ...
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const firestore = getFirestore(app);

CheckoutForm.js

import { collection, addDoc } from "firebase/firestore";
import { firestore } from "../../firebase";

export const CheckoutForm = async (uid) => {
  console.log("object 1")
  try {
    const docRef = await addDoc(collection(firestore, "documents"), {
      first: "Ada",
      last: "Lovelace",
      born: 1815
    });
    console.log("Document written with ID: ", docRef.id);
  } catch (e) {
    console.error("Error adding document: ", e);
  }
  console.log("object 2")
}

Home.js

import { loadStripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-stripe-js"

const PUBLIC_KEY = "pkey_test_stripe"

const stripeTestPromise = loadStripe(PUBLIC_KEY);

export default function Home() {
return (
  <Elements stripe={stripeTestPromise}>
   <div> 
    <button onClick={() => CheckoutForm(currUser.uid)}>
       Upgrade to premium!
    </button>
   </div>
  </Elements>
);
}

排查方案

  • 补全Firebase初始化代码:firebase.js中缺少initializeApp的导入,需添加:

    import { initializeApp } from "firebase/app";
    

    未导入该方法会导致Firebase App初始化不完整,Firestore无法正常运行。

  • 正确处理async函数调用:CheckoutForm是异步函数,按钮点击时直接调用未处理Promise,可能导致异常被静默吞掉。修改点击事件:

    <button onClick={async () => await CheckoutForm(currUser.uid)}>
      Upgrade to premium!
    </button>
    

    通过await确保函数执行过程中的异常能被内部try/catch捕获。

  • 检查Firestore安全规则:确认Firestore规则允许当前用户写入documents集合,测试阶段可临时设置宽松规则验证:

    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if request.auth != null;
        }
      }
    }
    

    验证后需恢复为符合业务需求的严格规则。

  • 查看Network请求状态:在浏览器DevTools的Network面板过滤firestore.googleapis.com请求,检查是否有请求发出、是否处于pending状态,以此判断是网络问题还是SDK异常。

  • 统一Firebase SDK版本:确保所有Firebase相关依赖包(如firebase/app、firebase/firestore)的版本一致,版本不兼容可能导致静默错误。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:25:43