跪拜 Guibai
← All articles
Frontend · Uni-app · Unix

uni-app x Gets an Axios-Style Request Library with Cancellation, Unified Errors, and a useRequest Hook

By 前端梦工厂 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Cross-platform uni-app x projects get a request layer that handles cancellation, race conditions, and error normalization, so business code can rely on a single `HttpError` type instead of ad-hoc checks. The design also exposes UTS's type quirks, which any team using uni-app x should know about.

Summary

uView Pro X now includes a dedicated http library for uni-app x, written to follow axios's API and exported as `http`. It supports `http.create()` for deriving instances with deep-merged defaults, so multi-backend projects can split baseURL and timeout per instance. Interceptors are stored as arrays: later registrations don't override earlier ones, and returning `null` in the request chain cancels the request. Response interceptors each get the same response object; the last non-null return is the final result, which avoids the type-assertion pain UTS can cause in chained calls.

Cancellation is handled with a custom controller because `uni.request` returns a `RequestTask` with no Promise or `signal`. The library settles the Promise with `ERR_CANCELED` before calling `task.abort()`, since `uni` doesn't guarantee the `fail` callback. All failures reject a single `HttpError` with exactly four `code` values: `ERR_BAD_RESPONSE`, `ERR_NETWORK`, `ERR_CANCELED`, and `ERR_INTERCEPTOR`. The `useRequest` hook wraps request state and handles the usual race-condition problems: it numbers each `run`, discards stale results, cancels on unmount, and cancels the previous request on re-run. Upload and download share the same defaults and interceptors, and upload strips `content-type` automatically.

The library intentionally omits interceptor `eject`, async interceptors, auto retry, and state management. Those are left to the business layer. The accompanying guide also documents pitfalls specific to UTS, such as avoiding `e is HttpError` (breaks on H5) and using `as Promise<T>`.

Takeaways
— `http` is exported from uView Pro X; no separate install needed.
— `http.create(config)` derives instances that deep-merge defaults; interceptors are not inherited, so call `setupInterceptors(instance)` per instance.
— Interceptors are arrays, not single slots; later registrations don't override earlier ones, and a `null` return in the request chain cancels the request.
— Response interceptors each receive the same `HttpResponse`; the last non-null return becomes the final result, avoiding chained type assertions.
— Cancellation uses a custom controller: `abort()` first rejects with `ERR_CANCELED`, then calls `task.abort()`, because `uni.request` doesn't guarantee a `fail` callback.
— Errors are always `HttpError` with one of four codes: `ERR_BAD_RESPONSE`, `ERR_NETWORK`, `ERR_CANCELED`, `ERR_INTERCEPTOR`.
— `useRequest` handles tri-state, race-condition discarding via sequence numbers, unmount cancellation, and cancel-previous-on-rerun; `immediate` defaults to `false`.
— Upload strips `content-type` automatically; download without `filePath` returns `tempFilePath`.
— Avoid `e is HttpError` on H5 (breaks to `ReferenceError`); use `as` instead. Avoid `as Promise<T>` as runtime behavior can differ.
— `validateStatus` only accepts a function; pass `(): boolean => true` to allow all status codes.
— Canceled signals cannot be reused; create a new controller per request.
Conclusions

Array-based interceptors fix the silent override problem of single-slot designs, but the response chain's 'last non-null wins' rule means developers must be careful about which interceptor returns what.

The cancellation fallback is a direct response to `uni.request`'s incomplete abort behavior; settling before aborting ensures no Promise hangs, a pragmatic pattern for any API that lacks full abort support.

UTS's type system shapes the library's API: no `is` operator, no chained type assertions, and no distinction between `null` and missing values. These constraints are worth remembering when writing uni-app x code.

Concepts & terms
UTS
A TypeScript-like language used in uni-app x projects that compiles to native code across platforms. It has stricter type restrictions than standard TypeScript, disallowing constructs like the `is` operator and the `null` vs undefined distinction.
validateStatus
A callback that determines which HTTP status codes are treated as successful responses. The library's default accepts 2xx; passing a custom function lets you allow other ranges, but `null` isn't accepted in UTS.
From the discussion
Featured comments
Mapleeeeeee

Can you explain what vapor mode actually is? What are its usage scenarios?

前端梦工厂

It's a rendering mode, similar to Vue's virtual DOM mode.

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗