0

我有一个带有以下代码的应用程序来处理 HTTP 请求:

import { logout } from '../containers/App/actions';
import store from '../store';

/**
 * Parses the JSON returned by a network request
 *
 * @param  {object} response A response from a network request
 *
 * @return {object}          The parsed JSON from the request
 */
function parseJSON(response) {
  if (response.status === 204 || response.status === 205) {
    return null;
  }
  return response.json();
}

/**
 * Checks if a network request came back fine, and throws an error if not
 *
 * @param  {object} response   A response from a network request
 *
 * @return {object|undefined} Returns either the response, or throws an error
 */
function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

/**
 * Requests a URL, returning a promise
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 *
 * @return {object}           The response data
 */
export default function request(url, options) {
  const headers = {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    'Access-Control-Request-Headers': 'Content-Type, Authorization'
  };
  const token = localStorage.getItem('token');
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }
  const newOptions = {
    ...options,
    mode: 'cors',
    headers
  };
  return fetch(url, newOptions)
    .then(checkStatus)
    .then(parseJSON)
    .catch(err => {
      // check for 401 here and throw an action to clean the store and logout.
      console.log(err);
      if (err.response.status === 401) {
        store.dispatch(logout);
      }
      throw err;
    });
}

除其他外,处理程序检查错误代码并调度 LOGOUT 操作以清理存储和会话。我的注销操作定义为:

export function logout() {
  return {
    type: LOGOUT
  };
}

但是,代码没有按我的意愿工作。我dispatch(logout)导致以下错误:Error: Actions must be plain objects. Use custom middleware for async actions.

我该如何解决这个问题?

4

1 回答 1

1

您正在传递 dispatch 一个函数logout,因此它将显示此错误。你需要像这样编辑:

store.dispatch(logout();

更新:如果你想要logout一个异步函数,你可以更新这个函数:

function logout() {
  return async (dispatch) => {
    await logout();

    dispatch({
      type: LOGOUT,
    });
  };
}
 store.dispatch(logout());
于 2021-04-19T15:59:48.760 回答