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
YourCreateDbUserfunction doesn't return anything (it runs theset()operation but has noreturnstatement), so it defaults to returningundefined. If you're accidentally calling it like this somewhere in your code:CreateDbUser(userId, "Jane", "jane@example.com")();You're trying to invoke
undefinedas a function—exactly the error you're seeing. Theset()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 importsfirebase/appbut notfirebase/database, thedatabase()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 byset()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:
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");Return the promise and add error handling
Update your function to return the promise fromset()—this lets you handle success/error cases properly, and avoids issues if you ever useawaitwith 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/awaitor.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); } };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

