reactjs - Mobx 使用参数计算 (compulatedFn) 和 TypeScript - 这是什么?

标签 reactjs typescript mobx mobx-react

以下示例https://mobx.js.org/refguide/computed-decorator.html使用 TypeScript 会引发错误。

// Parameterized computed views:
// Create computed's and store them in a cache
import { observable } from "mobx"
import { computedFn } from "mobx-utils"

class Todos {
  @observable todos = []

  getAllTodosByUser = computedFn(function getAllTodosByUser(userId) {
    return this.todos.filter(todo => todo.user === userId))
  })
}

'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)

An outer value of 'this' is shadowed by this container.

将 tsconfig 的 noImplicitThis 设置为 false 可以解决此问题,但我的目的是将 noImplicitThis 设置为 true

有什么想法吗?谢谢!

最佳答案

注入(inject) this: Todos 将修复它。 TypeScript 不会提示,并且 this 将被正确键入。请注意,TS 编译器在编译为 JavaScript 时会删除 this 参数。

// Parameterized computed views:
// Create computed's and store them in a cache
import { observable } from "mobx"
import { computedFn } from "mobx-utils"

class Todos {
  @observable todos: ITodo[] = []

  getAllTodosByUser = computedFn(function getAllTodosByUser(this: Todos, userId: ITodo[]) {
    return this.todos.filter(todo => todo.user === userId))
  })
}

关于reactjs - Mobx 使用参数计算 (compulatedFn) 和 TypeScript - 这是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59264167/

相关文章:

javascript - 在 MST 中对于 Animated.Value、setInterval、需要 ('image.png' )使用什么类型?

javascript - React Router - 从未直接渲染

javascript - 为 ReactJS 包装遗留小部件

Angular/Typescript 在接口(interface)中从蛇形大小写转换为驼峰大小写

angular - 来自 ngrx/entity 的 SelectAll 没有选择任何东西

javascript - 如何跟踪 MobX 存储中的嵌套对象

javascript - 将 `undefined` 转换为 `map<string, AnonymousModel>` 时出错

javascript - 无法访问 e.target.id,即使当我在 React 中登录 e.target 时它就在那里

javascript - 无法对 Gatsby 站点中 Ant Design Table 中的列进行排序

typescript - 无法读取全局配置字符串