NervJS / taro

开放式跨端跨框架解决方案,支持使用 React/Vue/Nerv 等框架来开发微信/京东/百度/支付宝/字节跳动/ QQ 小程序/H5/React Native 等应用。 https://taro.zone/
https://docs.taro.zone/
Other
35.41k stars 4.78k forks source link

taro 1.1.1 regeneratorRuntime is not defined 报错 #1017

Closed zhangzhenfei closed 5 years ago

zhangzhenfei commented 5 years ago

问题描述 入口src/app.tsx已经引入import '@tarojs/async-await'

page/index/index.tsx中使用async await 报错

// 这里可以贴代码
async componentWillMount() {
    // const { data } = await request({ url: '/weapp/network/list' })
    // this.setState({ networks: data })
    let result = await Taro.getSystemInfo()
    console.log(result)
  }
// 这里可以贴代码
import './index.scss'

import { Button, ScrollView, Text, View } from '@tarojs/components'
import Taro, { Component, Config } from '@tarojs/taro'
import { add, asyncAdd, minus } from '../../actions/counter'

import { ComponentClass } from 'react'
import { connect } from '@tarojs/redux'
import qcloud from '../../vendor/wafer2-client-sdk/index'
import request from '../../utils/request'

// #region 书写注意
//
// 目前 typescript 版本还无法在装饰器模式下将 Props 注入到 Taro.Component 中的 props 属性
// 需要显示声明 connect 的参数类型并通过 interface 的方式指定 Taro.Component 子类的 props
// 这样才能完成类型检查和 IDE 的自动提示
// 使用函数模式则无此限制
// ref: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/20796
//
// #endregion

type PageStateProps = {
  counter: {
    num: number
  }
  networks: Array<Object>
}

type PageDispatchProps = {
  add: () => void
  dec: () => void
  asyncAdd: () => any
  asyncLogin: () => any
}

type PageOwnProps = {}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Index {
  props: IProps
}

@connect(
  ({ counter }) => ({
    counter
  }),
  dispatch => ({
    add() {
      dispatch(add())
    },
    dec() {
      dispatch(minus())
    },
    asyncAdd() {
      dispatch(asyncAdd())
    },
    asyncLogin() {
      const session = qcloud.Session.get()

      if (session) {
        // 第二次登录
        // 或者本地已经有登录态
        // 可使用本函数更新登录态
        qcloud.loginWithCode({})
      } else {
        // 首次登录
        qcloud.login({})
      }
    }
  })
)
class Index extends Component {
  /**
   * 指定config的类型声明为: Taro.Config
   *
   * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型
   * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string
   * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型
   */
  config: Config = {
    navigationBarTitleText: '铭骏驾校'
  }

  async componentWillMount() {
    // const { data } = await request({ url: '/weapp/network/list' })
    // this.setState({ networks: data })
    let result = await Taro.getSystemInfo()
    console.log(result)
  }

  componentWillReceiveProps(nextProps) {
    console.log(this.props, nextProps)
  }

  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  render() {
    return (
      <View className='index'>
        <Button className='add_btn' onClick={this.props.add}>
          +
        </Button>
        <Button className='dec_btn' onClick={this.props.dec}>
          -
        </Button>
        <Button className='dec_btn' onClick={this.props.asyncAdd}>
          async
        </Button>

        <Button
          className='login_btn'
          openType='getUserInfo'
          onGetUserInfo={this.props.asyncLogin}
        >
          登录
        </Button>

        <ScrollView
          className='scrollview'
          scrollY
          scrollWithAnimation
          style='height: 150px;'
        >
          <View style='height:150px;background-color:rgb(26,173,25);'>A</View>
          <View style='height:150px;background-color:rgb(39,130,215);'>B</View>
          <View style='height:150px;background-color:rgb(241,241,241);color: #333;'>
            C
          </View>
        </ScrollView>
      </View>
    )
  }
}

// #region 导出注意
//
// 经过上面的声明后需要将导出的 Taro.Component 子类修改为子类本身的 props 属性
// 这样在使用这个子类时 Ts 才不会提示缺少 JSX 类型参数错误
//
// #endregion

export default Index as ComponentClass<PageOwnProps, PageState>

期望行为 正常使用promise异步函数

报错信息

VM3610:1 thirdScriptError sdk uncaught third Error regeneratorRuntime is not defined ReferenceError: regeneratorRuntime is not defined at http://127.0.0.1:39581/appservice/pages/index/index.js:143:51 at http://127.0.0.1:39581/appservice/pages/index/index.js:170:6 at http://127.0.0.1:39581/appservice/pages/index/index.js:217:2 at require (http://127.0.0.1:39581/appservice/__dev__/WAService.js:1:701762) at :7:7 at HTMLScriptElement.scriptLoaded (http://127.0.0.1:39581/appservice/appservice?t=1541510408009:1172:23)

系统信息

补充信息

define("pages/index/index.js", function(require, module, exports, window,document,frames,self,location,navigator,localStorage,history,Caches,screen,alert,confirm,prompt,fetch,XMLHttpRequest,WebSocket,webkit,WeixinJSCore,Reporter,print,URL,DOMParser,upload,preview,build,showDecryptedInfo,syncMessage,checkProxy,showSystemInfo,openVendor,openToolsLog,showRequestInfo,help,showDebugInfoTable,closeDebug,showDebugInfo,__global,WeixinJSBridge){ "use strict";

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () {
  function defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
    }
  }return function (Constructor, protoProps, staticProps) {
    if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
  };
}();

var _get = function get(object, property, receiver) {
  if (object === null) object = Function.prototype;var desc = Object.getOwnPropertyDescriptor(object, property);if (desc === undefined) {
    var parent = Object.getPrototypeOf(object);if (parent === null) {
      return undefined;
    } else {
      return get(parent, property, receiver);
    }
  } else if ("value" in desc) {
    return desc.value;
  } else {
    var getter = desc.get;if (getter === undefined) {
      return undefined;
    }return getter.call(receiver);
  }
};

var _class, _temp2;

var _tslib = require("../../npm/tslib/tslib.js");

var tslib_1 = _interopRequireWildcard(_tslib);

var _index = require("../../npm/@tarojs/taro-weapp/index.js");

var _index2 = _interopRequireDefault(_index);

var _counter = require("../../actions/counter.js");

var _index3 = require("../../npm/@tarojs/redux/index.js");

var _index4 = require("../../vendor/wafer2-client-sdk/index.js");

var _index5 = _interopRequireDefault(_index4);

function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}

function _interopRequireWildcard(obj) {
  if (obj && obj.__esModule) {
    return obj;
  } else {
    var newObj = {};if (obj != null) {
      for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
      }
    }newObj.default = obj;return newObj;
  }
}

function _asyncToGenerator(fn) {
  return function () {
    var gen = fn.apply(this, arguments);return new Promise(function (resolve, reject) {
      function step(key, arg) {
        try {
          var info = gen[key](arg);var value = info.value;
        } catch (error) {
          reject(error);return;
        }if (info.done) {
          resolve(value);
        } else {
          return Promise.resolve(value).then(function (value) {
            step("next", value);
          }, function (err) {
            step("throw", err);
          });
        }
      }return step("next");
    });
  };
}

function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError("Cannot call a class as a function");
  }
}

function _possibleConstructorReturn(self, call) {
  if (!self) {
    throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  }return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self;
}

function _inherits(subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass)));
  }subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}

var Index = (_temp2 = _class = function (_BaseComponent) {
  _inherits(Index, _BaseComponent);

  function Index() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, Index);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = Index.__proto__ || Object.getPrototypeOf(Index)).call.apply(_ref, [this].concat(args))), _this), _this.$usedState = ["add", "__fn_onClick", "dec", "asyncAdd", "asyncLogin", "__fn_onGetUserInfo"], _this.config = {
      navigationBarTitleText: '铭骏驾校'
    }, _this.$$refs = [], _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(Index, [{
    key: "_constructor",
    value: function _constructor() {
      _get(Index.prototype.__proto__ || Object.getPrototypeOf(Index.prototype), "_constructor", this).apply(this, arguments);
      /**
       * 指定config的类型声明为: Taro.Config
       *
       * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型
       * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string
       * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型
       */
    }
  }, {
    key: "componentWillMount",
    value: function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
        var result;
        return regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return _index2.default.getSystemInfo();

              case 2:
                result = _context.sent;

                console.log(result);

              case 4:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function componentWillMount() {
        return _ref2.apply(this, arguments);
      }

      return componentWillMount;
    }()
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      console.log(this.props, nextProps);
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {}
  }, {
    key: "componentDidShow",
    value: function componentDidShow() {}
  }, {
    key: "componentDidHide",
    value: function componentDidHide() {}
  }, {
    key: "_createData",
    value: function _createData() {
      this.__state = arguments[0] || this.state || {};
      this.__props = arguments[1] || this.props || {};
      ;
      Object.assign(this.__state, {});
      return this.__state;
    }
  }, {
    key: "funPrivateHCDSM",
    value: function funPrivateHCDSM() {
      this.__triggerPropsFn("add", [].concat(Array.prototype.slice.call(arguments)));
    }
  }, {
    key: "funPrivateRmoeB",
    value: function funPrivateRmoeB() {
      this.__triggerPropsFn("dec", [].concat(Array.prototype.slice.call(arguments)));
    }
  }, {
    key: "funPrivateNvpZf",
    value: function funPrivateNvpZf() {
      this.__triggerPropsFn("asyncAdd", [].concat(Array.prototype.slice.call(arguments)));
    }
  }, {
    key: "funPrivateSpZzi",
    value: function funPrivateSpZzi() {
      this.__triggerPropsFn("asyncLogin", [].concat(Array.prototype.slice.call(arguments)));
    }
  }]);

  return Index;
}(_index.Component), _class.properties = {
  "add": {
    "type": null,
    "value": null
  },
  "__fn_onClick": {
    "type": null,
    "value": null
  },
  "dec": {
    "type": null,
    "value": null
  },
  "asyncAdd": {
    "type": null,
    "value": null
  },
  "asyncLogin": {
    "type": null,
    "value": null
  },
  "__fn_onGetUserInfo": {
    "type": null,
    "value": null
  }
}, _class.$$events = ["funPrivateHCDSM", "funPrivateRmoeB", "funPrivateNvpZf", "funPrivateSpZzi"], _temp2);
Index = tslib_1.__decorate([(0, _index3.connect)(function (_ref3) {
  var counter = _ref3.counter;
  return {
    counter: counter
  };
}, function (dispatch) {
  return {
    add: function add() {
      dispatch((0, _counter.add)());
    },
    dec: function dec() {
      dispatch((0, _counter.minus)());
    },
    asyncAdd: function asyncAdd() {
      dispatch((0, _counter.asyncAdd)());
    },
    asyncLogin: function asyncLogin() {
      var session = _index5.default.Session.get();
      if (session) {
        // 第二次登录
        // 或者本地已经有登录态
        // 可使用本函数更新登录态
        _index5.default.loginWithCode({});
      } else {
        // 首次登录
        _index5.default.login({});
      }
    }
  };
})], Index);
// #region 导出注意
//
// 经过上面的声明后需要将导出的 Taro.Component 子类修改为子类本身的 props 属性
// 这样在使用这个子类时 Ts 才不会提示缺少 JSX 类型参数错误
//
// #endregion
exports.default = Index;
});
luckyadam commented 5 years ago

麻烦提一下 app.tsx 代码

zhangzhenfei commented 5 years ago
import '@tarojs/async-await'
import './app.scss'

import Taro, { Component, Config } from '@tarojs/taro'

import Index from './pages/index'
import { Provider } from '@tarojs/redux'
import config from './config'
import configStore from './store'

const store = configStore()

class App extends Component {
  /**
   * 指定config的类型声明为: Taro.Config
   *
   * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型
   * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string
   * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型
   */
  config: Config = {
    pages: ['pages/index/index', 'pages/profile/index'],
    window: {
      backgroundTextStyle: 'light',
      navigationBarBackgroundColor: '#5DA374',
      navigationBarTitleText: 'WeChat',
      navigationBarTextStyle: 'white'
    },
    tabBar: {
      color: '#5DA374',
      selectedColor: '#5DA374',
      borderStyle: 'white',
      backgroundColor: '#FEFEFE',
      list: [
        {
          text: '主页',
          pagePath: 'pages/index/index',
          iconPath: 'static/img/tabbar/homepage.png',
          selectedIconPath: 'static/img/tabbar/homepage_fill.png'
        },
        {
          text: '我的',
          pagePath: 'pages/profile/index',
          iconPath: 'static/img/tabbar/addressbook.png',
          selectedIconPath: 'static/img/tabbar/addressbook_fill.png'
        }
      ]
    }
  }
  componentWillMount() {
    /**
     * 小程序初始化时执行,我们初始化客户端的登录地址,以支持所有的会话操作
     */
    const qcloud = require('./vendor/wafer2-client-sdk/index')
    qcloud.setLoginUrl(config.service.loginUrl)
  }

  componentDidMount() {}

  componentDidShow() {}

  componentDidHide() {}

  componentCatchError() {}

  componentDidCatchError() {}

  // 在 App 类中的 render() 函数没有实际作用
  // 请勿修改此函数
  render() {
    return (
      <Provider store={store}>
        <Index />
      </Provider>
    )
  }
}

Taro.render(<App />, document.getElementById('app'))

@luckyadam

luckyadam commented 5 years ago

没有复现,有没有按这个处理 https://nervjs.github.io/taro/docs/before-dev-remind.html#%E5%B0%8F%E7%A8%8B%E5%BA%8F

zhangzhenfei commented 5 years ago

非常感谢,原来是因为开启了es6转es5引起的,不好意思~

yuhong-l commented 5 years ago

非常感谢,原来是因为开启了es6转es5引起的,不好意思~

为啥开了es6转5会有这个问题鸭? 我没开还是有同样的错误。

liudonghua123 commented 5 years ago

我也是这个问题

yuhong-l commented 5 years ago

我也是这个问题

xjb 删掉重新install 几次就好了

LucaLJX commented 5 years ago

如果不开es6转 es5 引入vant组件库就会报错