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

NextJS14项目中Redux Toolkit2.0无法更新用户状态求助

问题:Redux Toolkit 2.0 未正确将用户数据更新到指定状态属性

我正在开发基于NextJS14的电商应用,使用Redux Toolkit 2.0进行状态管理。按照RTK2.0语法创建了用户切片,用于获取用户数据并更新状态。API请求正常,能从数据库获取用户数据,访问localhost:3000/api/user也能看到数据,但Redux DevTools显示数据仅存于新增的data属性中,未更新到初始定义的user状态对象。

相关代码

用户切片代码

"use client";

import { buildCreateSlice, asyncThunkCreator } from "@reduxjs/toolkit";

const createSliceWithThunks = buildCreateSlice({
  creators: {
    asyncThunk: asyncThunkCreator,
  },
});

const initialState = {
  user: {
    _id: "",
    fname: "",
    lname: "",
    email: "",
    streetAddress: "",
    postalCode: "",
    city: "",
    county: "",
    country: "",
  },
  loading: false,
  error: null,
};

const userSlice = createSliceWithThunks({
  name: "user",
  initialState,
  reducers: (create) => ({
    fetchUser: create.asyncThunk(
      async (_, thunkApi) => {
        const response = await fetch("/api/user");
        if (!response.ok) {
          throw new Error("Failed to fetch user data");
        }
        const userData = await response.json();
        console.log(userData);
        return userData;
      },
      {
        pending: (state) => {
          (state.loading = true), (state.error = null);
        },
        fulfilled: (state, action) => {
          state.loading = false;
          state.data = action.payload;
        },
        rejected: (state, action) => {
          state.loading = false;
          state.error = action.error.message;
        },
      }
    ),
  }),
});

export const { fetchUser } = userSlice.actions;
export default userSlice.reducer;

API路由代码(api/user/route.js)

import { connectDb } from "@dbConfig/db";
import User from "@models/UserModel";
import { getServerSession } from "next-auth";
import { NextResponse } from "next/server";

export async function GET(req, res) {
  const session = getServerSession(); //使用NextAuth会话数据获取邮箱以在MongoDB中查找用户

  try {
    const email = (await session).user.email; //Prettier自动格式化该行,修改会导致代码报错

    connectDb();

    const user = await User.findOne({ email });
    console.log(user);

    return NextResponse.json({ message: "User found:", user }, { status: 201 });
  } catch (error) {
    console.log(error);
  }
}

问题现象

Redux DevTools显示状态结构如下:
Redux DevTools截图
可以看到新增了data字段存储返回的用户数据,但初始定义的user对象未被更新。

解决方案

问题出在两个地方:

  1. 状态赋值错误:在fetchUser的fulfilled回调中,你将返回的数据赋值给了state.data,但初始状态里并没有这个属性,应该赋值给state.user。
  2. API返回数据结构处理错误:你的API返回的是{ message: "User found:", user },所以实际的用户数据在action.payload.user中,而非整个action.payload。

修改后的fulfilled回调代码:

fulfilled: (state, action) => {
  state.loading = false;
  // 正确赋值到state.user,并取API返回的user字段
  state.user = action.payload.user;
}

修改后,Redux状态中的user对象会被正确更新,data字段不会再被新增。

内容的提问来源于stack exchange,提问作者Leslie W.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 14:19:54