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

使用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.js onSubmit function, you're calling dispatch(updateUserData(firstName, lastName))
  • But your updateUserData action creator is defined to take dispatch and getState as parameters
  • When using Redux Thunk, the middleware automatically injects dispatch and getState into action creators that return functions. By manually passing firstName and lastName, you're overwriting those injected parameters:
    • firstName is being treated as the dispatch argument
    • lastName (your value "Stephanson") is being treated as the getState argument
  • 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:

  1. You're not sending the user's input data to the backend at all
  2. Your Axios put request has incorrect syntax for headers
  3. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:35:26