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

React Redux TypeScript类型设置:thunk函数与action的正确类型定义

问题核心原因
  1. Redux Toolkit的slice中没有给setCountries的action payload定义类型,导致TS推断该action不需要传参,触发参数不匹配报错
  2. fetch返回数据的类型定义错误、dispatch的类型定义错误,同时存在未定义的any类型

解决步骤

1. 修正slice代码

首先给state和action payload补充类型定义:

import { createSlice, PayloadAction } from '@reduxjs/toolkit';

// 定义state类型
interface CountryListState {
  countryList: string[];
}

const initialState: CountryListState = {
    countryList: [],
};

const slice = createSlice({
    name: 'countryList',
    initialState,
    reducers: {
        // 指定payload为字符串数组类型,和存储的_id类型匹配
        setCountries(state, action: PayloadAction<string[]>) {
            state.countryList = action.payload;
        },
    },
});

export const { setCountries } = slice.actions;
export default slice.reducer;

如果你的_id是number类型,把上面所有string替换成number即可。

2. 修正fetchCountries thunk代码

修正dispatch类型、接口定义,移除所有any:

// 替换为你项目中store导出的实际路径
import { AppDispatch } from './store';

interface FetchedCountries {
    mergedArray?: Array<{ _id: string }>;
}

export const fetchCountries = () => {
    // dispatch类型替换为官方导出的AppDispatch
    return (dispatch: AppDispatch) => {
        console.log(dispatch)
        fetch(countryListJsonFile)
            .then((response) => response.json())
            .then((jsonData: FetchedCountries) => {
                // 替换冗余的Object.entries写法,加空值判断避免运行时报错
                const countries = jsonData.mergedArray?.map(el => el._id).sort() || [];
                dispatch(setCountries(countries));
            })
            .catch(function (err) {
                console.error(err);
            });
    };
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 12:09:01