使用redux-thunk时触发TypeError: middleware is not a function错误的原因是什么?
问题:redux-thunk传入applyMiddleware时报错"middleware is not a function"
错误信息
return middleware(middlewareAPI); ^ TypeError: middleware is not a function
代码片段
import { createStore, applyMiddleware } from 'redux' import thunk from 'redux-thunk' import reducer from "./reducers.js"; const store = createStore(reducer, applyMiddleware(thunk))
原因分析
问题出在redux-thunk的版本导入方式上:redux-thunk v3.0.0及以后的版本采用了ES模块的命名导出,不再提供默认导出。你现在用import thunk from 'redux-thunk'导入的是一个包含thunk属性的对象,而非真正的中间件函数,传给applyMiddleware自然会触发“middleware is not a function”的错误。
解决方案
改用命名导入的方式获取真正的thunk中间件:
import { createStore, applyMiddleware } from 'redux' import { thunk } from 'redux-thunk' import reducer from "./reducers.js"; const store = createStore(reducer, applyMiddleware(thunk))
如果需要兼容旧版本写法(不推荐),也可以手动提取默认导出:
import thunk from 'redux-thunk' const actualThunk = thunk.default; const store = createStore(reducer, applyMiddleware(actualThunk))
内容的提问来源于stack exchange,提问作者Bimal Sunil
相关产品推荐
相关产品推荐

