Vue.js + Firebase点击按钮删用户报错:this.usersRef.delete不是函数
Got it, let's break down what's going wrong here and get your user deletion working properly.
The Root Cause
Your this.usersRef is almost certainly a Firestore collection reference (like firebase.firestore().collection('users')), and collection references don't have a delete() method—this method only exists on individual document references. Also, you're mixing up two separate Firebase operations: deleting the user from Firebase Authentication, and deleting their corresponding data from Firestore.
Corrected Code
Here's how to fix your function to handle both steps correctly:
deleteUser() { const authUser = firebase.auth().currentUser; // First, make sure there's a current user to delete if (!authUser) { console.log("No active user found to delete"); return; } // Step 1: Delete the user's document from Firestore this.usersRef.doc(authUser.uid).delete() .then(() => { console.log("User data deleted from Firestore"); // Step 2: Delete the user from Firebase Authentication return authUser.delete(); }) .then(() => { console.log("User successfully deleted from both Firestore and Auth"); }) .catch((error) => { console.error("Error during user deletion:", error); }); }
Key Changes Explained
- Target the specific document: Instead of calling
delete()on the entireusersRefcollection, we use.doc(authUser.uid)to get the reference to the current user's individual document, then calldelete()on that. - Separate Auth and Firestore operations: Deleting the Auth user is done via
authUser.delete()(a method on the authenticated user object), not through your Firestore reference. We chain these operations to ensure both steps complete (or fail gracefully).
Important Note: Recent Login Requirement
Firebase requires users to have logged in recently to delete their own account (to prevent unauthorized deletions). If you hit an error like auth/requires-recent-login, you'll need to re-authenticate the user first. Here's a quick example for email/password users:
deleteUser() { const authUser = firebase.auth().currentUser; if (!authUser) { console.log("No active user found to delete"); return; } // Get the user's password (you'll need to collect this from your UI) const userPassword = "user-input-password"; const credential = firebase.auth.EmailAuthProvider.credential( authUser.email, userPassword ); // Re-authenticate first, then proceed with deletion authUser.reauthenticateWithCredential(credential) .then(() => { return this.usersRef.doc(authUser.uid).delete(); }) .then(() => { return authUser.delete(); }) .then(() => { console.log("User deleted successfully"); }) .catch((error) => { console.error("Error deleting user:", error); }); }
内容的提问来源于stack exchange,提问作者DenisMasot

