Javascript React.js:您使用不可调用的回调调用了`setState`

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31400468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:39:48  来源:igfitidea点击:

React.js :You called `setState` with a callback that isn't callable

javascriptreactjs

提问by Fleeck

This is my piece of code, which works correctly (adds records), but throws an error after addition:

这是我的一段代码,它工作正常(添加记录),但添加后抛出错误:

Uncaught Error: Invariant Violation: enqueueCallback(...): You called setProps, replaceProps, setState, replaceState, or forceUpdatewith a callback that isn't callable.

Uncaught Error: Invariant Violation: enqueueCallback(...): You call setProps, replaceProps, setState, replaceState, 或 forceUpdate使用不可调用的回调。

handleSubmit: function(e) {
    e.preventDefault();
    return $.post('', {page: this.state},
      function(data) {
        this.props.handleNewPage(data);
        return this.setState(this.getInitialState(), 'JSON');
      }.bind(this)
    );
  }

There are no routes for now. Can someone help me to solve this?

目前没有路线。有人可以帮我解决这个问题吗?

回答by Madara's Ghost

The second (optional) parameter to setStateis a callback function, not a string. You can pass a function that will be executed once the operation is completed.

第二个(可选)参数setState是回调函数,而不是字符串。您可以传递一个将在操作完成后执行的函数。

回答by Hannes Johansson

You actually invoke getInitialStateinstead of providing a reference to the function itself on the line return this.setState(this.getInitialState(), 'JSON');and the second argument should never be anything but a callback function.

您实际上是在调用getInitialState而不是在行上提供对函数本身的引用,return this.setState(this.getInitialState(), 'JSON');并且第二个参数不应该只是回调函数。

this.setStateexpects either a function that should return a state object as a single argument, or an object to merge the current state with (plus optionally a callback as a second argument to run after state has been set). So either you provide just a function that returns the new state, or you provide an object that the current state should be merged with as a first argument and a callback that will be executed after the state has been set as second argument.

this.setState期望一个函数应该返回一个状态对象作为单个参数,或者一个对象来合并当前状态(加上可选的回调作为第二个参数在状态设置后运行)。因此,您要么只提供一个返回新状态的函数,要么提供一个对象,该对象应将当前状态合并为第一个参数,并在将状态设置为第二个参数后执行回调。

Either this.setState(this.getInitialState)or this.setState(this.getInitialState())or this.setState(newState, callback).

无论是this.setState(this.getInitialState)this.setState(this.getInitialState())this.setState(newState, callback)

Check out the signature in the API here.

此处查看 API 中的签名。