React传递函数作为参数报错:React-Redux Firestore表单回调异常
Let's break down why you're seeing this error and how to fix it step by step.
Root Cause
The error TypeError: func is not a function occurs because when your Action tries to call func() in the Firestore set() success callback, the func parameter isn't a valid function (it's almost certainly undefined). Let's trace this back to your code.
Step 1: Ensure the Function Reference is Passed Correctly
First, check how you're passing this.successMessage to UpdateUserDetails in handleSubmit. While successMessage is an arrow function (so this is correctly bound), there might be edge cases where the function reference isn't being passed properly.
Quick Fix: Wrap the Function Call
Instead of passing this.successMessage directly, wrap it in an arrow function to guarantee it's sent as a valid function reference:
// Inside the .then(url => { ... }) block of handleSubmit this.props.UpdateUserDetails(uid, stateObj, () => this.successMessage())
Step 2: Validate Your Redux Connect Configuration
Make sure your component is correctly mapping the UpdateUserDetails action creator to props. If you're using connect, double-check your mapDispatchToProps:
If you're using the object shorthand (most common):
// Correct implementation export default connect(mapStateToProps, { UpdateUserDetails })(YourComponent);
If you're writing mapDispatchToProps manually:
const mapDispatchToProps = dispatch => ({ UpdateUserDetails: (id, droneSPDetails, func) => dispatch(UpdateUserDetails(id, droneSPDetails, func)) });
If this mapping is missing or incorrect, the func parameter won't reach your Action properly.
Step 3: Fix the Async State Update Bug (Bonus)
While unrelated to your current error, you have a subtle bug in handleSubmit: setState is asynchronous, so when you do:
this.setState({ sp_License: url }); const stateObj = this.state;
stateObj will still hold the old sp_License value (the file object, not the download URL). Fix this by either:
- Building the state object directly with the URL:
.then(url => { const stateObj = { ...this.state, sp_License: url }; this.props.UpdateUserDetails(uid, stateObj, this.successMessage); });
- Using
setState's callback to ensure state is updated before accessing it:
.then(url => { this.setState({ sp_License: url }, () => { const stateObj = this.state; this.props.UpdateUserDetails(uid, stateObj, this.successMessage); }); });
Step 4: Debug with Console Logs
To confirm what's happening, check the console.log(func) in your Action. If it logs undefined, that confirms the function isn't being passed correctly. If it logs a function but still throws the error, there might be a rare this binding issue (though arrow functions make this unlikely).
内容的提问来源于stack exchange,提问作者ansh

