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

Next.js+TypeScript中Redux Toolkit异步Thunk派发参数报错解决

解决Next.js+TypeScript中Redux Toolkit无法派发createAsyncThunk的类型错误

问题根源

报错Expected 0 arguments, but got 1.ts(2554)的核心原因是**useAppDispatch定义错误**:你在hooks.ts中返回的是useDispatch<AppDispatch>函数本身,而非调用它得到的dispatch实例。这导致TypeScript无法正确识别dispatch的类型,进而无法处理带参数的async thunk。

修复步骤

1. 修正hooks.ts中的useAppDispatch

将useDispatch<AppDispatch>改为调用形式useDispatch<AppDispatch>():

import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import { AppDispatch, RootState } from "./store";

// 修复:添加()调用useDispatch函数
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

2. 确保store.ts中正确定义AppDispatch

若你的store.ts未正确导出AppDispatch,需补充以下配置:

import { configureStore } from "@reduxjs/toolkit";
import userReducer from "./slices/UserSlice";

export const store = configureStore({
  reducer: {
    user: userReducer,
  },
});

// 导出包含异步thunk类型的dispatch类型
export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;

3. 组件代码无需修改

修复hooks后,组件中原先的派发代码可正常运行:

import { useAppDispatch } from "../redux/hooks";
import { auth } from "../redux/slices/UserSlice";

const dispatch = useAppDispatch();
onClick={() => {
  dispatch(auth({ email, password })); // 不再报错
}}

原理说明

  • useDispatch<AppDispatch>()会返回类型为AppDispatch的dispatch实例,而AppDispatch包含了Redux Toolkit异步thunk的类型信息,能正确识别auth这个async thunk的参数类型。
  • 之前的写法返回的是() => AppDispatch类型的函数,而非dispatch实例,因此调用dispatch(auth(...))时,TypeScript会判定你在调用一个无参函数,从而抛出参数不匹配的错误。

内容的提问来源于stack exchange,提问作者Saad Vakil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 13:30:50