【问题标题】:action creator with thunk in typescript-redux, sees the action as undefined在 typescript-redux 中使用 thunk 的动作创建者,将动作视为未定义
【发布时间】:2021-03-03 12:30:00
【问题描述】:

为了解决这个错误,我已经工作了大约 4 个小时:

export const fetchUsers: ActionCreator<ThunkAction<
  Promise<FetchUserActions>, //type of last action
  User[], // The type for the data within the last action
  null, //extra argument
  FetchUserActions
>> = () => {
  return async (dispatch: Dispatch<AppActions>) => {
    try {
      // ususally action creators returns an obj. but this is an api request and thunk will take over, make the request and then dispatch the res.data
      const res: AxiosResponse<User[]> = await axios.get<User[]>("/users");
      if (res && res.data) {
        return dispatch({ type: ActionTypes.fetchUsers, payload: res.data });
      }
    } catch (error) {
      console.log(error);
    }
  };
};

我收到了这些错误:

 Type 'Promise<{ type: ActionTypes.fetchUsers; payload: User[]; } | undefined>' is not assignable to type 'Promise<FetchUserActions>'.
 
Type '{ type: ActionTypes.fetchUsers; payload: User[]; } | undefined' is not assignable to type 'FetchUserActions'.

Type 'undefined' is not assignable to type 'FetchUserActions'.ts(2322)

打字稿很简单,但我很难理解解释。我不明白这个 undefined 来自哪里。

export interface FetchUserActions extends Action {
  type: ActionTypes.fetchUsers;
  payload: User[];
}

【问题讨论】:

    标签: reactjs typescript redux redux-thunk


    【解决方案1】:

    undefined 是因为当您的 axios 响应中有错误时,您 catch 没有任何错误并且不返回任何内容(即 undefined)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-18
      • 2020-05-23
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      • 2019-08-14
      • 2020-11-21
      相关资源
      最近更新 更多