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

如何将redux-token-auth的方法从组件移至Action文件?

解决redux-token-auth在自定义Redux Action中调用认证方法的类型错误

我明白你遇到的问题了——把组件里的认证逻辑抽离到单独的Action文件是非常合理的实践,但这里的核心问题是你没正确处理signInUser和signOutUser作为Redux Thunk action creators的特性。

问题根源

在官方示例里,signInUser是通过connect的第二个参数(mapDispatchToProps)注入到组件props中的,React-Redux会自动把这个action creator包装成已绑定dispatch的函数,所以你在组件里直接调用signInUser({ email, password })就能触发对应的Redux流程。

但在你的自定义Action文件里,直接调用signInUser({ email, password })只会返回一个未执行的thunk函数,并没有让Redux Thunk中间件去处理它,自然会抛出类型错误或者不执行预期的API请求。

修复方案

你需要在自定义的thunk action里,通过dispatch来调用signInUser和signOutUser——因为它们本身就是thunk action creators,必须经过dispatch才能被中间件处理。

修改你的/actions/auth.js代码如下:

// /actions/auth.js
import { signInUser, signOutUser } from '../redux-token-auth-config'

export const Login = (email, password) => {
  return (dispatch) => {
    dispatch(LoginStart());
    // 关键:用dispatch调用signInUser,它会返回Promise
    dispatch(signInUser({ email, password }))
      .then((response) => dispatch(LoginSuccess(response.data.data)))
      .catch((error) => dispatch(LoginError(error)));
  };
};

export const LoginStart = () => ({ type: 'LOGIN::START' });
export const LoginSuccess = (data) => ({ type: 'LOGIN::SUCCESS', payload: data });
export const LoginError = (error) => ({ type: 'LOGIN::ERROR', payload: error })

export const Logout = () => {
  return (dispatch) => {
    dispatch(SessionCleanup())
    // 同样用dispatch调用signOutUser
    dispatch(signOutUser())
      .then((response) => console.log('Success'))
      .catch((error) => console.log(error))
  }
}

export const SessionCleanup = () => ({ type: 'LOGIN::SESSION_CLEANUP' })

额外注意事项

  • 确保你的Redux store已经正确配置了Redux Thunk中间件,这是所有thunk action正常工作的前提:
    import { createStore, applyMiddleware } from 'redux';
    import thunk from 'redux-thunk';
    import rootReducer from './reducers';
    
    const store = createStore(rootReducer, applyMiddleware(thunk));
    
  • signInUser返回的Promise会包含认证请求的响应数据,你可以直接在then里获取response并分发自定义的成功action。
  • 如果使用TypeScript,检查你的类型定义是否正确识别signInUser的返回值为Promise,同时确保自定义action的类型和reducer逻辑匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:31:12