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

ReactJs集成Firebase时set()报错但数据写入正常问题排查

Hey there! Let's break down this weird, confusing issue you're facing—your data saves successfully to Firebase, but you're hitting a "Object(...)(...) is undefined" TypeError. Super frustrating, right? Let's dig into why this is happening and how to fix it for good.

Possible Causes

Let's start with the most likely culprits:

  • Extra parentheses when calling your function
    Your CreateDbUser function doesn't return anything (it runs the set() operation but has no return statement), so it defaults to returning undefined. If you're accidentally calling it like this somewhere in your code:

    CreateDbUser(userId, "Jane", "jane@example.com")();
    

    You're trying to invoke undefined as a function—exactly the error you're seeing. The set() operation still runs successfully (since it starts before the error throws), but that extra pair of parentheses is causing the TypeError.

  • Firebase import/initialization mismatch
    If you're using Firebase v9+ (the modular SDK) but sticking to the old namespace syntax (firebase.database()), you might have forgotten to import the database compat module. For example, if your Firebase setup only imports firebase/app but not firebase/database, the database() method could be undefined on first call—even if the operation eventually succeeds due to late loading or caching.

  • Missing promise handling
    While this doesn't directly cause the "undefined" error, not handling the promise returned by set() means you're blind to any future failures. It's a good practice to fix this alongside the core issue.

Fixes to Try

Let's tackle these one by one:

  1. Check how you're calling CreateDbUser
    Scan every place you use this function and remove any extra parentheses. For example:

    // ❌ Wrong (extra parentheses)
    CreateDbUser(123, "John", "john@example.com")();
    
    // ✅ Correct
    CreateDbUser(123, "John", "john@example.com");
    
  2. Return the promise and add error handling
    Update your function to return the promise from set()—this lets you handle success/error cases properly, and avoids issues if you ever use await with it:

    export const CreateDbUser = (id, username, email) => {
      return firebase.database().ref(`users/${id}`).set({ username, email })
        .catch(error => {
          console.error("Failed to save user data:", error);
          throw error; // Re-throw if you want the caller to handle the error
        });
    };
    

    Then when calling it, use async/await or .then() for clean async handling:

    const handleCreateUser = async (id, username, email) => {
      try {
        await CreateDbUser(id, username, email);
        console.log("User saved successfully!");
      } catch (error) {
        console.error("Error saving user:", error);
      }
    };
    
  3. Fix Firebase imports (if using v9+)
    If you're using Firebase v9+ compat mode (to keep the old syntax), make sure you import the database module in your Firebase setup file:

    import firebase from 'firebase/compat/app';
    import 'firebase/compat/database'; // Don't skip this line!
    
    const firebaseConfig = { /* your Firebase config */ };
    firebase.initializeApp(firebaseConfig);
    

    If you want to switch to the modern modular API (recommended for performance), rewrite your function like this:

    import { getDatabase, ref, set } from "firebase/database";
    
    export const CreateDbUser = (id, username, email) => {
      const db = getDatabase();
      return set(ref(db, `users/${id}`), { username, email })
        .catch(error => {
          console.error("Save failed:", error);
          throw error;
        });
    };
    

Final Note

Even though the data saves now, this error is a red flag for fragile code. Fixing the function's return value and invocation pattern will eliminate the TypeError and make your code more reliable for future changes.

内容的提问来源于stack exchange,提问作者Maël.L

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:56:46