【问题标题】:Unable to dispatch redux actions in axios success response interceptor无法在 axios 成功响应拦截器中调度 redux 操作
【发布时间】:2021-06-22 09:12:09
【问题描述】:

通常我们在 Axios 错误响应拦截器中调度操作,它工作正常

axiosInstance.interceptors.response.use(
    (next) => {
        return Promise.resolve(next);
    },
    (error) => {
// Dispatching to handle error 1
        if (error.response.status === 401) {
            if (error.response.data.errorCode === 'USER_LOGIN_ERROR_008') {
                store.dispatch({ type: 'RESET_SECURITY_QUESTION', payload: { id: null, qid: null, question: null } });
            }
     throw error;
    }
);

每个成功的 API 响应都会在用户的 cookie 中设置一个令牌,如果在接下来的 X 分钟内没有调用任何 API,则该令牌将过期

因此,在每次成功的 API 响应之后,我需要在我的 App.js 中启动一个计时器,一旦该计时器结束,就会向用户显示一个模态,表明他的会话已失效

但是,如果用户的操作导致 API 调用成功,那么我想重置该计时器

要重置该计时器,我想在每次成功的 API 响应后调用一个 redux 操作

这就是我尝试做的事情

axiosInstance.interceptors.response.use(
    (next) => {
        console.log(`Intercepting ${next.config.url} success response`, next);
        if (next.status === 200) {
             store.dispatch(incrementSessionRefreshTimer());
        }

        return Promise.resolve(next);
    },

这里有问题

每当我们使用 axios 拦截器拦截成功请求时,我们可以修改请求并且必须将请求返回

在我的代码中发生的情况是,我的操作已被调度,但响应从未返回,store.dispatch(myAction()) 下方没有任何行被执行,因此我进行 API 调用的组件没有获得成功响应

有什么解决方法吗?

【问题讨论】:

    标签: javascript reactjs redux axios


    【解决方案1】:

    该代码肯定应该在该分派之后继续执行。它可能会导致立即重新渲染,在这种情况下,重新渲染可能发生在下一行之前,但除非在任何地方抛出异常,否则return Promise.resolve(next);执行。我认为您的问题出在其他地方。

    【讨论】:

    • 我也在我的失败响应拦截器中调度了许多动作(条件调度处理注销错误、401 错误、400 错误等),并且代码在 store.dispatch(action ()) 也行
    • 将其包装在 try { dispatch(...) } catch (e) { console.log(e) } 块中。还要在下一行放置一个console.log("test")。通常:这是 JavaScript。方法不会突然停止执行。这只发生在return 语句或抛出错误时。否则那简直是不可能的。那里没有特定于 Redux 的内容。
    • 我按照你所说的将store.dispatch( . . . ) 包裹在try catch 中,并发现reducer 中存在错误,因此代码被破坏了。现在 action 被调度,Reducer 正在改变状态并且响应也被返回给组件。谢谢。
    猜你喜欢
    • 2020-11-21
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 2017-05-28
    • 2019-03-27
    • 2018-11-27
    相关资源
    最近更新 更多