用 redux-saga 的 race 效应实现请求超时取消。

解读

国内中高级前端面试常把“网络请求超时处理”作为 saga 实战能力的试金石。
题目看似只问 race,实则考察四点:

  1. 是否理解 race 的短路特性——谁先结束谁获胜,其余任务自动取消;
  2. 能否把“业务请求”与“超时信号”抽象成两个可取消的 Effect;
  3. 是否熟悉 call + cancel + delay 组合 的写法,避免手写 setTimeout 导致不可测试;
  4. 异常或取消后是否主动触发失败 Action,保证 Redux 状态闭环。
    答出“race 用法”只能及格,给出“可测试、可复用、状态闭环”的完整模板才能拿到高分。

知识点

  • race(effects):并行启动多个 Effect,最快完成的那个结果作为返回值,其余自动取消。
  • call(fn, ...args):阻塞调用,返回 Promise,可被 cancel。
  • delay(ms):官方工具函数,返回一个定时 Promise,可被 cancel,比 setTimeout 更适合测试。
  • cancel(task):手动取消任务;在 race 里失败方会被框架自动 cancel,无需手动处理。
  • try/catch + finally:捕获网络异常,无论成功或取消都要 dispatch 结束 Action,防止按钮一直 loading。
  • redux-saga 测试方案:国内团队普遍使用 @redux-saga/testing-utils 或 redux-saga-test-plan,delay 与 call 均返回普通对象,可断言 race 的分支。

答案

// services/api.js
export const fetchUser = id =>
  axios.get(`/api/user/${id}`).then(res => res.data);

// sagas/user.js
import { race, call, put, delay } from 'redux-saga/effects';
import { fetchUser } from '@/services/api';
import { userSuccess, userFail } from '@/actions/user';

export function* fetchUserSaga(action) {
  const { id } = action.payload;
  try {
    // 5000 ms 超时
    const { data, timeout } = yield race({
      data: call(fetchUser, id),
      timeout: delay(5000)
    });

    if (timeout) {
      // 超时分支获胜
      yield put(userFail({ id, reason: '网络超时' }));
      return;
    }

    // 正常返回
    yield put(userSuccess({ id, data }));
  } catch (e) {
    // 网络错误、非 2xx 状态码等
    yield put(userFail({ id, reason: e.message }));
  }
}

// 监听
export function* watchFetchUser() {
  yield takeEvery('USER_REQUEST', fetchUserSaga);
}

关键点说明

  1. race 返回对象 key 与放入时一致,通过解构直接拿到 data 或 timeout。
  2. delay 返回的 Promise 永远不会 reject,超时只会进入 timeout 分支,不会走 catch。
  3. 无论哪条分支获胜,另一条 Effect 会被自动取消,axios 请求对应的 CancelToken 也会被回收,不会造成内存泄漏。
  4. 在 try 外部再包一层 catch,兜底网络异常,保证任何错误都能落到 userFail,维持 Redux 状态一致性。

拓展思考

  1. 动态超时:把超时时间放到 action.payload 或全局配置里,通过 call(delay, timeout) 实现 不同接口不同阈值。
  2. 请求竞态取消:如果组件重复触发 USER_REQUEST,可用 takeLatest 代替 takeEvery,旧请求自动取消,与 race 超时形成双层保护。
  3. 重试策略:超时后可在 catch/finally 里判断 if (reason === '网络超时') yield retry(3, 1000, fetchUser, id),结合 race 与 retry 实现指数退避。
  4. 测试用例:使用 redux-saga-test-plan
    return expectSaga(fetchUserSaga, { payload: { id: 1 } })
      .provide([[call.fn(fetchUser), delay(100)]], [delay(5000), true]])
      .put(userFail({ id: 1, reason: '网络超时' }))
      .run();
    
    无需真实请求即可断言 race 超时分支,契合国内 CI 环境。