【问题标题】:react _this2.setState is not a function - possible binding issuereact _this2.setState 不是函数 - 可能的绑定问题
【发布时间】:2018-12-16 20:05:03
【问题描述】:

我是超级新手,我一直在努力找出导致chrome console 中此错误的原因

bundle.js:15316 Uncaught (in promise) TypeError: _this2.setState is not a function

我正在尝试使用 facebook 对 web 应用进行简单的登录,以了解登录流程。

我已经在/(也是我的home 页面路由)上设置了我的登录名。我不认为问题出在路由或其他任何地方。这似乎是 react 中的 binding 的问题,并且是这个框架的新手 - 我很难弄清楚如何解决这个问题。

我的/home 路由jsx 看起来像这样

import React, { Component } from "react";
import { browserHistory } from 'react-router';
import FacebookLogin from 'react-facebook-login';


export default class Home extends Component {

    constructor() {
        super();
        this.state = { isAuthenticated: false, user: null, token: ''};
        this.setInputState = this.setInputState.bind(this);
    }

    /*logout = () => {
        this.setState({isAuthenticated: false, token: '', user: null})
    };*/

    responseFacebook(response) {
      console.log(response)
      const accessTokenBlob = new Blob([JSON.stringify({input_token: response.accessToken}, null, 2)], {type : 'application/json'});
      const options = {
          method: 'POST',
          body: accessTokenBlob,
          //mode: 'cors',
          cache: 'default'
      };
      fetch('http://localhost:8880/auth/facebook', options)
          .then((r) => r.json())
          .then(r => {
            console.log(r)
            if (r.status) {
                this.setState({isAuthenticated: true, user: response.id, token: response.accessToken})
            }
      });
    }

    componentDidMount() {
        browserHistory.push('/');
    }
    render() {
        console.log(this.state)
        let content = this.state.isAuthenticated ?
        (
            <div>
                <p>Authenticated</p>
                <div>
                    {this.state.user.name}
                </div>
                <div>
                    <button onClick={this.logout} className="button">
                        Log out
                    </button>
                </div>
            </div>
        ) : (
            <div>
            <FacebookLogin
                appId="2128489194096154"
                autoLoad={true}
                fields="name,id,picture"
                scope="public_profile"
                callback={this.responseFacebook} />
            </div>
        );
        return (
            <div className="App">
                {content}
            </div>
        );
    }
}

问题似乎发生在包含这部分代码 this.setState({isAuthenticated: true, user: response.id, token: response.accessToken})

的行上

当我在浏览器的控制台上设置debug 时,我看到这是this2 错误堆栈链接中的替换内容:

fetch('http://localhost:8880/auth/facebook', options).then(function (r) {
                return r.json();
            }).then(function (r) {
                console.log(r);
                if (r.status) {
                    _this2.setState({ isAuthenticated: true, user: response.id, token: response.accessToken });
                }
            });

我已经在这个问题上待了将近一天,我完全迷失了 - 已经阅读了几篇文章 - 并且没有得到任何结果。当我一直在努力解决这个问题时,如果问题不清楚 - 请让我知道我可以添加哪些更多细节。


编辑#1

http://localhost:8880/auth/facebook 这是我写的后端,这是我控制的。后端的响应日志和前端收到的数据是一样的。这告诉我cors 或其他集成问题没有问题。

【问题讨论】:

  • 像这样使用箭头函数responseFacebook = (response) =&gt; {
  • 在线包含这个callback={this.responseFacebook} /&gt;也绑定responsefacebook函数。
  • 感谢@PrakashSharma - 您的解决方案似乎对我有用。

标签: javascript reactjs react-native react-router react-redux


【解决方案1】:

responseFacebook 函数未绑定到 class 上下文。所以this里面responseFacebook函数不引用class。你可以像这样使用箭头函数

responseFacebook = (response) => {

或者你可以像这样显式地bindconstructor中的函数

    constructor() {
        super();
        this.state = { isAuthenticated: false, user: null, token: ''};
        this.setInputState = this.setInputState.bind(this);
        this.responseFacebook = this.responseFacebook.bind(this);
    }

【讨论】:

  • 你知道我为什么会遇到这个错误吗?使用arrow function 的第一种方法? ERROR in ./src/components/views/home.jsx Module build failed: SyntaxError: Unexpected token (23:21) 21 | };*/ 22 | &gt; 23 | responseFacebook = (response) =&gt; { | ^
  • 你的第二种方法对我有用,我理解问题是什么,也更好地学习了语义。谢谢你的帮助。但我非常好奇为什么箭头功能对我不起作用,任何帮助/指导将不胜感激。
  • @sudhishkr 它显示语法错误。你确定你的语法是正确的吗?把代码改成箭头函数后能显示吗?
  • 代码共享链接:codeshare.io/50P18N(24 小时后到期 - 因为我不想修改我的问题)
  • 酷不用担心,我会继续在这方面进行挖掘。你解决了我的问题..谢谢你的帮助。选择您对此问题的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-24
  • 2020-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-14
相关资源
最近更新 更多