You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-Query传递TodoService方法报错:this.get不是函数的原因解析

理解React-Query传递类方法时的this指向问题

问题现象

构建了用于HTTP请求的TodoService类,其getAllTodos方法会调用父类HttpService的get方法。当把todoService.getAllTodos直接作为React-Query的useQuery第二个参数时,会报错TypeError: this.get is not a function at Object.getAllTodos;但用箭头函数包裹成() => todoService.getAllTodos()传递时,就能正常获取服务器数据。

原因分析

这是JavaScript函数this绑定机制导致的问题:

  • 类中的普通方法(比如getAllTodos())的this是调用时动态绑定的。当你直接把todoService.getAllTodos作为函数传递给useQuery时,这个方法会脱离原实例上下文执行,此时this不再指向todoService实例(严格模式下会变成undefined),自然找不到this.get方法。
  • 用箭头函数() => todoService.getAllTodos()传递时,getAllTodos是通过todoService实例调用的,方法内的this会正确绑定到todoService,因此能正常调用父类的get方法。

解决方案

有两种常用的解决方式:

方式1:用箭头函数包裹传递

在useQuery中通过箭头函数间接调用实例方法,确保this指向正确:

import { todoService } from '../../../servecies/todo.servecies';

export const TodoContainer = () => {
  const { data, error, isLoading, isError } = useQuery('todos', () => todoService.getAllTodos());
};

方式2:将类方法改为箭头函数属性

箭头函数的this是定义时绑定的,会永久指向类实例,这样即使单独传递方法,this也不会丢失:

import { HttpSerivce } from './http.servicies';

class TodoService extends HttpSerivce {
  constructor() {
    super();
  }

  // 改为箭头函数类属性
  getAllTodos = async () => {
    return this.get({ url: 'todos' });
  }
}

export const todoService = new TodoService();

相关代码参考

HttpService父类代码

import axios from 'axios';

type Config = {
  url: string;
};

export class HttpSerivce {
  baseUrl: string | undefined;
  fetchingService: any;
  apiVersion: string;

  constructor(baseUrl = 'http://localhost:4200', fetchingService = axios, apiVersion = 'api') {
    this.baseUrl = baseUrl;
    this.fetchingService = fetchingService;
    this.apiVersion = apiVersion;
  }

  async get(config: Config) {
    const response = await this.fetchingService.get(`http://localhost:4200/api/${config.url}`);
    return response.data;
  }
}

内容的提问来源于stack exchange,提问作者Paul Gutsal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 10:15:38