Skip to main content
Version: 10.x

中止过程调用

默认情况下,tRPC 不会通过 React Query 取消请求。如果你想选择此行为,你可以在配置中提供 abortOnUnmount

¥By default, tRPC does not cancel requests via React Query. If you want to opt into this behaviour, you can provide abortOnUnmount in your configuration.

注意

@tanstack/react-query only supports aborting queries.

全局地

¥Globally

client.ts
ts
// @filename: utils.ts
import { createTRPCReact } from '@trpc/react-query';
 
export const trpc = createTRPCReact<AppRouter>({
abortOnUnmount: true,
});
 
trpc.createClient({
// ...
});
client.ts
ts
// @filename: utils.ts
import { createTRPCReact } from '@trpc/react-query';
 
export const trpc = createTRPCReact<AppRouter>({
abortOnUnmount: true,
});
 
trpc.createClient({
// ...
});

预请求

¥Per-request

你还可以在查询级别覆盖此行为。

¥You may also override this behaviour at the query level.

Twoslash failure

Errors were thrown in the sample, but not included in an errors tag

These errors were not marked as being expected: 2307 7031.
Expected: // @errors: 2307 7031

Compiler Errors:

server/router.ts
[2307] 25 - Cannot find module '@trpc/server' or its corresponding type declarations.
[7031] 230 - Binding element 'input' implicitly has an 'any' type.

utils/trpc.ts
[2307] 45 - Cannot find module '@trpc/react-query' or its corresponding type declarations.

Raising Code:

// @filename: server/router.ts
// @include: router
// @filename: utils/trpc.ts
// ---cut---
import { createTRPCReact } from '@trpc/react-query';
import type { AppRouter } from '../server/router';

export const trpc = createTRPCReact<AppRouter>();

// @filename: pages/posts.tsx
declare const useRouter: any;
// ---cut---
import { trpc } from '../utils/trpc';

function PostViewPage() {
  const { query } = useRouter();
  const postQuery = trpc.post.byId.useQuery(
    { id: query.id },
    { trpc: { abortOnUnmount: true } }
  );

  // ...
}