使用Express更新MongoDB用户数据时遇getState非函数错误求助
Hey there, let's break down what's causing this error and fix it step by step!
错误根源
First, let's unpack that error message: getState is not a function. (In 'getState()','getState' is 'Stephanson') — this is a classic parameter mismatch issue.
Here's what's happening:
- In your
FullName.jsonSubmitfunction, you're callingdispatch(updateUserData(firstName, lastName)) - But your
updateUserDataaction creator is defined to takedispatchandgetStateas parameters - When using Redux Thunk, the middleware automatically injects
dispatchandgetStateinto action creators that return functions. By manually passingfirstNameandlastName, you're overwriting those injected parameters:firstNameis being treated as thedispatchargumentlastName(your value "Stephanson") is being treated as thegetStateargument
- So when your code tries to run
getState(), it's actually trying to call a string like'Stephanson'()— which obviously isn't a function.
On top of that, there are two hidden issues preventing your update from working even if the error was fixed:
- You're not sending the user's input data to the backend at all
- Your Axios
putrequest has incorrect syntax for headers - Your backend update controller doesn't actually process the update — it just returns the existing user data
Step-by-Step Fixes
1. Fix the Action Creator & Its Call
First, adjust your action creator to accept the user's form data, and let Redux Thunk handle injecting dispatch and getState:
// userActions.js export function updateUserData(userData) { // Return a function that will receive dispatch/getState from Redux Thunk return (dispatch, getState) => { const state = getState(); const { user_id, token } = state.auth; // Fix Axios put syntax: request body comes 2nd, headers go in the 3rd config object return axios.put(USER_DATA(user_id), userData, { headers: { authorization: token } }).then((response) => { console.log('Updated user data:', response.data.data.firstName); dispatch(setUserData(response.data.data)); }).catch((err) => { console.error("Couldn't update user data:", err); // Optional: Dispatch an error action for your UI to handle // dispatch(setUpdateError(err.message)); }); } } export const setUserData = (userData) => ({ type: 'SET_USER_DATA', userData });
Then update the call in FullName.js to pass the full form values:
// FullName.js const onSubmit = (values, dispatch) => { console.log('Submitting form values:', values); // Pass the entire form values object to the action creator dispatch(updateUserData(values)); };
2. Fix the Backend Update Controller
Your current backend controller just returns the existing user — it doesn't actually update anything. Here's how to fix it (assuming you're using Mongoose; adjust for your ORM/ODM):
// Authentication_controller.js exports.update = async function (req, res, next) { try { // Extract the data to update from the request body const { firstName, lastName } = req.body; // Find the user and update their data (return the updated document) const updatedUser = await User.findByIdAndUpdate( req.user._id, // Use req.user from your requireAuth middleware, or req.params.user_id { firstName, lastName }, { new: true, runValidators: true } ); if (!updatedUser) { return res.status(404).json({ error: 'User not found' }); } res.json({ data: updatedUser }); } catch (err) { next(err); } };
3. Verify Redux Thunk is Configured
Make sure your Redux store has the Thunk middleware enabled — without it, action creators that return functions won't work:
// store.js import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import rootReducer from './reducers'; const store = createStore( rootReducer, applyMiddleware(thunk) ); export default store;
4. Optional: Improve Reducer Initial State
Your reducer starts with an empty array, but user data is an object. Adjust it for better consistency:
// userDatareducer.js module.exports = (state = {}, action) => { switch (action.type) { case 'SET_USER_DATA': return action.userData; case 'UPDATE_USER_DATA': // For partial updates, merge existing state with new data instead of replacing return { ...state, ...action.userData }; default: return state; } };
After making these changes, the getState is not a function error should disappear, and your user data update flow will work as intended.
内容的提问来源于stack exchange,提问作者Markus Hayner

