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

Redux学习问题:Node.js中redux-thunk默认导出导入报错

Redux-Thunk 导入错误解决方案

问题详情

在Node.js项目中使用ES模块(已在package.json设置"type": "module")配置Redux-Thunk时,出现导出错误:

SyntaxError: The requested module 'redux-thunk' does not provide an export named 'default'

错误栈信息:

at ModuleJob._instantiate (node:internal/modules/esm/module_job:132:21)
at async ModuleJob.run (node:internal/modules/esm/module_job:214:5)
at async ModuleLoader.import (node:internal/modules/esm/loader:329:24)
at async loadESM (node:internal/modules/esm/module_loader:34:7)
at async handleMainPromise (node:internal/modules/run_main:113:12)

用户代码片段:

import {createStore,applyMiddleware} from 'redux';
import thunk from 'redux-thunk'
import axios from 'axios';

const store = createStore(reducer, applyMiddleware(thunk.default));

function reducer(state={title:"Hello"},action){
    if(action.type === 'ch'){
        return {amount: action.payload};
    }
    return state;
}

async function change(dispatch,getState){
    const {data} = await axios.get('http://localhost:3000/1');
    dispatch(changeUser(data.title))
}

function changeUser(value){
    return {type:'ch',payload:value}
}

store.dispatch(change);

console.log(store.getState());

尝试直接使用applyMiddleware(thunk)时同样报错。


解决方案

1. 修正Redux-Thunk导入方式

Redux-Thunk v2.x及以上版本仅提供命名导出,不存在默认导出,需改用命名导入:

import { thunk } from 'redux-thunk';

2. 正确配置Store

修改Store创建代码,直接传入导入的thunk:

const store = createStore(reducer, applyMiddleware(thunk));

完整修正代码

import {createStore,applyMiddleware} from 'redux';
import { thunk } from 'redux-thunk';
import axios from 'axios';

const store = createStore(reducer, applyMiddleware(thunk));

function reducer(state={title:"Hello"},action){
    if(action.type === 'ch'){
        return {amount: action.payload};
    }
    return state;
}

async function change(dispatch,getState){
    const {data} = await axios.get('http://localhost:3000/1');
    dispatch(changeUser(data.title))
}

function changeUser(value){
    return {type:'ch',payload:value}
}

store.dispatch(change);

console.log(store.getState());

额外建议

如果使用现代Redux方案(Redux Toolkit),无需手动配置Thunk——Redux Toolkit默认集成了Thunk中间件,配置更简洁:

import { configureStore } from '@reduxjs/toolkit';
import reducer from './reducer';

const store = configureStore({ reducer });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 13:31:09