typescript 如何在useEffect钩子中使用局部作用域?

w3nuxt5m  于 2023-01-14  发布在  TypeScript
关注(0)|答案(1)|浏览(80)

下面的代码工作正常:

useEffect(() => {
  const apiService = new APIClient('api address');
  var topicCommentsReq = new GetTopicDetailsRequest();
  topicCommentsReq.setTopicCid(Buffer.from("123", "hex"));
  apiService.getTopicDetails(topicCommentsReq, {}, function (err, response) {
    console.log(`response : ${JSON.stringify(response)}`);
  });
}

我想把这个回调风格的函数转换成async/await风格,所以我做了如下的事情:

const promisifyFn =
  (fn: Function) =>
  (...args: any[]) =>
    new Promise((resolve, reject) => {
      return fn(...args, (err: Error, data: any) => {
        return err ? reject(err) : resolve(data);
      });
    });

useEffect(() => {
  (async () => {
    const apiService = new APIClient("api address");
    const topicCommentsReq = new GetTopicDetailsRequest();
    topicCommentsReq.setTopicCid(Buffer.from("123", "hex"));
    const getTopicDetails = promisifyFn(apiService.getTopicDetails);
    try {
      const res = await getTopicDetails(topicCommentsReq, {});
      console.log(`response : ${JSON.stringify(res)}`);
    } catch (e) {
      console.log(e);
    }
  })();
});

显示以下错误消息:

TypeError: Cannot read properties of undefined (reading 'client_')
 if (callback !== undefined) {
      return this.client_.rpcCall(
        this.hostname_ +
          '/StelaPlatform.GRPC.API/GetTopicDetails',
        request,
        metadata || {},
        this.methodDescriptorGetTopicDetails,
        callback);
    }

我猜这个问题与lcoal作用域有关。当函数在async函数中运行时,this作用域是不同的。但是我应该如何解决这个问题呢?

h79rfbju

h79rfbju1#

问题是在将函数引用传递给apiService.getTopicDetails时,它丢失了它的this上下文。
为了使prototype函数保持在其原型中,您应该使用箭头函数...

const getTopicDetails = promisifyFn((...args) =>
  apiService.getTopicDetails(...args));

Function.prototype.bind()

const getTopicDetails = promisifyFn(apiService.getTopicDetails.bind(apiService));

相关问题