本文不定时更新中……
收集了一些在开发过程中遇到的一些问题的解决方法,适合新手。
异常:
出现脚本错误或者未正确调用 Page()
原因:不小心删了第一行内容:<template>
异常:
模块编译失败:TypeError: Cannot read property 'for' of undefined
at fixDefaultIterator (D:\HBuilderX\plugins\uniapp\lib\mpvue-template-compiler\build.js:4277:24)
at mark (D:\HBuilderX\plugins\uniapp\lib\mpvue-template-compiler\build.js:4306:5)
at markComponent (D:\HBuilderX\plugins\uniapp\lib\mpvue-template-compiler\build.js:4371:5)
at baseCompile (D:\HBuilderX\plugins\uniapp\lib\mpvue-template-compiler\build.js:4384:15)
at compile (D:\HBuilderX\plugins\uniapp\lib\mpvue-template-compiler\build.js:4089:28)
at Object.module.exports (D:\HBuilderX\plugins\uniapp\lib\mpvue-loader\lib\template-compiler\index.js:43:18)
原因:新建的页面(简单模板)只有以下 3 个标签,须在 <template /> 中添加一些代码,如 <view />
<template>
</template>
<script>
</script>
<style>
</style>异常:
模块编译失败:TypeError: Cannot read property 'toString' of undefined
at Object.preprocess (D:\HBuilderX\plugins\uniapp\lib\preprocess\lib\preprocess.js:56:15)
at Object.module.exports (D:\HBuilderX\plugins\uniapp\lib\preprocessor-loader.js:9:25)
原因:没有原因,纯抽风,HX 关掉再开就好了。
异常:
Cannot set property 'xxx' of undefined;at pages/... onLoad function;at api request success callback function
原因:属性未定义,例如
data() {
return {
item: { }
}
}而直接赋值 this.item.abc.xxx = '123';
解决:
data() {
return {
item: {
abc: ''
}
}
}问:page 页面怎样修改 tabBar?
答:官方文档未给出答案,百度了一圈也无果(2018-10-23),但有人说小程序的 setTabBarBadge() 方法设置角标是可以用的。
坑:
VM1694:1 获取 wx.getUserInfo 接口后续将不再出现授权弹窗,请注意升级
参考文档: https://developers.weixin.qq.com/community/develop/doc/0000a26e1aca6012e896a517556c01
填坑:放弃使用 uni.getUserInfo 接口来获取用户信息,uni.login 可返回用于换取 openid / unionid 的 code,参:uni.login、 code2Session
坑:字符搜索(当前目录)(Ctrl+Alt+F)搜不出所有结果
填坑:顾名思义他只搜索当前目录,即当前打开文件所在目录,而非我误认为的整个项目根目录。在“项目管理器”中选中要搜索字符的目录即可。
坑:uni.navigateTo() 或 uni.redirectTo() 没反应
填坑:这两个方法不允许跳转到 tabbar 页面,用 uni.switchTab() 代替。
坑:使用“Ctrl+/”快捷键弹出“QQ五笔小字典”窗口
解决:打开QQ五笔“属性设置”,切换到“快捷键设置”选项卡,把“五笔小字典”前的勾取消(即使该组合键是设置为Ctrl+?)。
坑:<rich-text /> 中的 <img /> 太大,超出屏幕宽度
填坑:用正则表达式给 <img /> 加上最大宽度
data.data.Content = data.data.Content.replace(/\<img/gi, '<img style="max-width:100%;height:auto" ');坑:无法重命名或删除目录或文件
填坑一:“以管理员身份运行”HBuilder X 后再试。
填坑二:关闭微信开发者工具、各种手机和模拟器后再试。
填坑三:打开“任务管理器”,结束所有“node.exe”进程后再试。
坑:
thirdScriptError
sdk uncaught third Error
(intermediate value).$mount is not a function
TypeError: (intermediate value).$mount is not a function
Page[pages/xxxx/xxxx] not found. May be caused by: 1. Forgot to add page route in app.json. 2. Invoking Page() in async task.
Page is not constructed because it is not found.填坑:关闭微信开发者工具、各种手机和模拟器后,删除“unpackage”目录。
坑:
Unexpected end of JSON input;at "pages/news/view" page lifeCycleMethod onLoad function
SyntaxError: Unexpected end of JSON input填坑:给 uni.navigateTo() 的 url 传参时,如果简单地将对象序列化 JSON.stringify(item),那么如果内容中包含“=”等 url 特殊字符,就会发生在接收页面 onLoad() 中无法获取到完整的 json 对象,发生异常。
uni.navigateTo({
url: "../news/view?item=" + JSON.stringify(item)
})所以应该把参数值编码:
uni.navigateTo({
url: "../news/view?item=" + escape(JSON.stringify(item))
})如果是一般的 web 服务器来接收,那么会自动对参数进行解码,但 uni-app 不会,如果直接使用:
onLoad(e) {
this.item = JSON.parse(e.item);
}会发生异常:
Unexpected token % in JSON at position 0;at "pages/news/view" page lifeCycleMethod onLoad function
SyntaxError: Unexpected token % in JSON at position 0需要解码一次:
onLoad(e) {
this.item = JSON.parse(unescape(e.item));
}需要注意的是,unescape(undefined) 会变成 'undefined',如果要判断是否 undefined,应是 unescape 之前。
坑:图片变形
填坑:mode="widthFix"
坑:页面如何向 tabBar 传参
填坑:全局或缓存
坑:编译为 H5 后,出现:Access-Control-Allow-Origin
填坑:参阅
坑:编译为 H5 后,GET 请求的 URL 中出现“?&”
填坑 :客户端只求 DCloud 官方能够尽快修复这个 bug,IIS 端可以暂时用 URL 重写来防止报 400 错误,参此文。
坑:[system] errorHandler TypeError: Cannot read property 'forEach' of undefined
填坑:待填
制作类似下图中的拖拽排序功能:

1. 首先数据库该表中添加字段 sort,类型为 double(MySQL 中为 double(0, 0))。
2. 页面输出绑定数据(以 ASP.NET MVC 控制器为例):
public ActionResult EditSort()
{
if (!zConsole.Logined) { return RedirectToAction("", "SignIn", new { redirect = Request.Url.OriginalString }); }
db_auto2018Entities db = new db_auto2018Entities();
return View(db.dt_dealer.Where(c => c.enabled).OrderBy(c => c.sort));
}这里可以加条件列出,即示例中 enabled == true 的数据。
3. 前台页面引用 jQuery 和 jQuery UI。
4. 使用 <ul /> 列出数据:
<ul id="sortable" class="list-group gutter list-group-lg list-group-sp">
@foreach (var d in Model)
{
<li class="list-group-item" draggable="true" data-id="@d.id">
<span class="pull-left"><i class="fa fa-sort text-muted fa m-r-sm"></i> </span>
<div class="clear">
【id=@d.id】@d.name_full
</div>
</li>
}
</ul>5. 初始化 sortable,当拖拽结束时保存次序:
<script>
var url_SaveSort = '@Url.Action("SaveSort")';
</script>
<script>
$("#sortable").sortable({
stop: function (event, ui) {
// console.log('index: ' + $(ui.item).index())
// console.log('id: ' + $(ui.item).data('id'))
// console.log('prev_id: ' + $(ui.item).prev().data('id'))
$.post(url_SaveSort, {
id: $(ui.item).data('id'),
prev_id: $(ui.item).prev().data('id')
}, function (json) {
if (json.result.success) {
// window.location.reload();
} else {
toastr["error"](json.result.info);
}
}, 'json');
}
});
$("#sortable").disableSelection();
</script>这里回传到服务端的参数为:当前项的 id 值、拖拽后其前面一项的 prev_id 值(若移至首项则 prev_id 为 undefined)。
不使用 $(ui.item).index() 是因为,在有筛选条件的结果集中排序时,使用该索引值配合 LINQ 的 .Skip 会引起取值错误。
6. 控制器接收并保存至数据库:
[HttpPost]
public ActionResult SaveSort(int id, int? prev_id)
{
if (!zConsole.Logined)
{
return Json(new { result = new { success = false, msg = "请登录后重试!" } }, JsonRequestBehavior.AllowGet);
}
db_auto2018Entities db = new db_auto2018Entities();
dt_dealer d = db.dt_dealer.Find(id);
// 拖拽后其前项 sort 值(若无则 null)(此处不需要加 enabled 等筛选条件)
double? prev_sort = prev_id.HasValue
? db.dt_dealer.Where(c => c.id == prev_id).Select(c => c.sort).Single()
: null as double?;
// 拖拽后其后项 sort 值(若无前项则取首项作为后项)(必须强制转化为 double?,否则无后项时会返回 0,导致逻辑错误)
double? next_sort = prev_id.HasValue
? db.dt_dealer.Where(c => c.sort > prev_sort && c.id != id).OrderBy(c => c.sort).Select(c => (double?)c.sort).FirstOrDefault()
: db.dt_dealer.Where(c => c.id != id).OrderBy(c => c.sort).Select(c => (double?)c.sort).FirstOrDefault();
if (prev_sort.HasValue && next_sort.HasValue)
{
d.sort = (prev_sort.Value + next_sort.Value) / 2;
}
if (prev_sort == null && next_sort.HasValue)
{
d.sort = next_sort.Value - 1;
}
if (prev_sort.HasValue && next_sort == null)
{
d.sort = prev_sort.Value + 1;
}
db.SaveChanges();
return Json(new { item = new { id = d.id }, result = new { success = true } });
}需要注意的是,当往数据库添加新项时,必须将 sort 值设置为已存在的最大 sort 值 +1 或最小 sort 值 -1。
var d = new dt_dealer
{
name_full = "新建项",
sort = (db.dt_dealer.Max(c => (double?)c.sort) ?? 0) + 1,
};当我们初始化一个 Swiper 时,
var mySwiper = new Swiper ('.swiper-container');
如果页面上只有一个 .swiper-container,那么 mySwiper 是一个对象,如果有多个 .swiper-container,则 mySwiper 是一个数组。
处理不当会报以下错误:
Uncaught TypeError: Cannot read property 'appendSlide' of undefined
Uncaught TypeError: Cannot read property 'prependSlide' of undefined
如果 .NET Core 项目发布到服务器上报以下错误:
HTTP Error 502.5 - Process Failure
Common causes of this issue:
The application process failed to start
The application process started but then stopped
The application process started but failed to listen on the configured port
Troubleshooting steps:
Check the system event log for error messages
Enable logging the application process' stdout messages
Attach a debugger to the application process and inspect
For more information visit: https://go.microsoft.com/fwlink/?LinkID=808681
在服务器上安装最新的 .NET Core Runtime 即可(Windows Server 选择 Hosting Bundle Installer)。
获取
在 NuGet 中搜索 ZXing.Net
简单示例
var qr = new ZXing.QrCode.QRCodeWriter();
var matrix = qr.encode("http://xoyozo.net/", ZXing.BarcodeFormat.QR_CODE, 200, 200);
var writer = new ZXing.BarcodeWriter()
{
Format = ZXing.BarcodeFormat.QR_CODE
};
Bitmap bitmap = writer.Write(matrix);扩展示例
string content = "http://xoyozo.net/";
var hints = new Dictionary<ZXing.EncodeHintType, object>();
hints.Add(ZXing.EncodeHintType.ERROR_CORRECTION, ZXing.QrCode.Internal.ErrorCorrectionLevel.H); // 纠错级别
hints.Add(ZXing.EncodeHintType.CHARACTER_SET, Encoding.Default.WebName); // 编码:gb2312
hints.Add(ZXing.EncodeHintType.MARGIN, 0); // 出血码元数(标准为 4,美观为 2)
var qr = new ZXing.QrCode.QRCodeWriter();
var matrix = qr.encode(content, ZXing.BarcodeFormat.QR_CODE, 200, 200, hints);
var writer = new ZXing.BarcodeWriter()
{
Format = ZXing.BarcodeFormat.QR_CODE,
Renderer = new ZXing.Rendering.BitmapRenderer
{
Foreground = Color.Black, // 前景色(默认黑色)
Background = Color.White, // 背景色(默认白色)
},
};
Bitmap bitmap = writer.Write(matrix);将 Bitmap 写入到流
Stream stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Png);将 Bitmap 保存到磁盘
string path = "D:\wwwroot\upload\abc.png";
bitmap.Save(path, ImageFormat.Png);更多
对比 ThoughtWorks.QRCode 和 ZXing.Net
获取
在 NuGet 中搜索 ThoughtWorks.QRCode
简单示例
var qr = new ThoughtWorks.QRCode.Codec.QRCodeEncoder();
Bitmap bitmap = qr.Encode("http://xoyozo.net/");扩展示例
string content = "http://xoyozo.net/";
var qr = new ThoughtWorks.QRCode.Codec.QRCodeEncoder
{
// 纠错级别,L (7%)、M (15%)、Q (25%)、H (30%)
QRCodeErrorCorrect = ThoughtWorks.QRCode.Codec.QRCodeEncoder.ERROR_CORRECTION.H,
// 码元尺寸(像素)
QRCodeScale = 4,
// 前景色(默认黑色)
QRCodeForegroundColor = Color.Black,
// 背景色(默认白色)
QRCodeBackgroundColor = Color.White,
};
// 根据内容确定 Mode,参:http://en.wikipedia.org/wiki/QR_code#Storage
if (Regex.IsMatch(content, @"^\d+$"))
{
qr.QRCodeEncodeMode = ThoughtWorks.QRCode.Codec.QRCodeEncoder.ENCODE_MODE.NUMERIC;
}
else if (Regex.IsMatch(content, @"^[0-9A-Z $%*+-./:]+$"))
{
qr.QRCodeEncodeMode = ThoughtWorks.QRCode.Codec.QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC;
}
else
{
qr.QRCodeEncodeMode = ThoughtWorks.QRCode.Codec.QRCodeEncoder.ENCODE_MODE.BYTE;
}
Bitmap bitmap = qr.Encode(content, Encoding.Default); // 编码,简体中文系统默认为 gb2312裁切掉多余的 1 像素
ThoughtWorks.QRCode 生成的四周没有留白的二维码图片,其右边和下边分别会多出 1 像素,使用以下方法来调整图片大小
// 创建一个新的图片(宽度和高度各缩小 1 像素)
Bitmap bitmap2 = new Bitmap(bitmap.Size.Width - 1, bitmap.Size.Height - 1);
// 以新图片来绘图
Graphics g2 = Graphics.FromImage(bitmap2);
// 新旧图片绘制到新图片中(左上角对齐)
g2.DrawImage(bitmap, 0, 0);将 Bitmap 写入到流
Stream stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Png);若已裁切 1 像素,请修改为 bitmap2
将 Bitmap 保存到磁盘
string path = "D:\wwwroot\upload\abc.png";
bitmap.Save(path, ImageFormat.Png);若已裁切 1 像素,请修改为 bitmap2
更多
对比 ThoughtWorks.QRCode 和 ZXing.Net
打开:\WeiXinMPSDK-master\src\Senparc.Weixin.MP.Sample\Senparc.Weixin.MP.Sample.sln
工具 - NuGet 包管理器 - 管理解决方案的 NuGet 程序包 - 更新
选择所有的包(Microsoft.Net.Http 无法更新,暂不勾选),更新
Microsoft.Net.Http 是个老顽固,无法更新也无法卸载,原因是它的语言包 Microsoft.Net.Http.zh-Hans 无法安装。我们切换到“已安装”选项卡,搜索“Microsoft.Net.Http”,选中 Microsoft.Net.Http.zh-Hans 并卸载它,现在我们可以更新 Microsoft.Net.Http 了。
【可能】运行报错:
“/”应用程序中的服务器错误。
配置错误
说明: 在处理向该请求提供服务所需的配置文件时出错。请检查下面的特定错误详细信息并适当地修改配置文件。
分析器错误消息: 创建 system.web.webPages.razor/host 的配置节处理程序时出错: 未能加载文件或程序集“System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35”或它的某一个依赖项。找到的程序集清单定义与程序集引用不匹配。 (异常来自 HRESULT:0x80131040)
源错误:行 4: <configSections>
行 5: <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
行 6: <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
行 7: <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
行 8: </sectionGroup>
源文件: E:\WeiXinMPSDK-master\src\Senparc.Weixin.MP.Sample\Senparc.Weixin.MP.Sample\views\web.config 行: 6展开 Senparc.Weixin.MP.Sample 引用,查看 System.Web.Razor 的属性,复制版本号。打开 \views\web.config,修改 System.Web.WebPages.Razor 的 Version(有 3 处)。
对于小型开发项目来说,我习惯将所有代码放在同一个项目(Project)中来,所以做了以下处理:(盛派官方分离这些代码是为了同时供 MVC 和 WebForms 重用)
在 Senparc.Weixin.MP.Sample 中添加文件夹 CommonService,将 Senparc.Weixin.MP.Sample.CommonService 项目中的文件夹和文件(.config 除外)拖到 CommonService 文件夹中。
卸载 Senparc.Weixin.MP.Sample.CommonService 项目并删除引用。
在解决方案的 Libraries 文件夹中,我们看到 Sample 项目了以下功能模块,这些就是 Senparc.Weixin 的源代码,如果不需要修改,可以卸载它们改为使用从 NuGet 获取,以便随时更新到最新版本:
Senparc.WebSocket
Senparc.Weixin
Senparc.Weixin.MP
Senparc.Weixin.MP.MvcExtension NuGet 中对应的包名为:Senparc.Weixin.MP.MVC
Senparc.Weixin.Open
Senparc.Weixin.Work
Senparc.Weixin.WxOpen
Senparc.Weixin.Cache.Memcached
Senparc.Weixin.Cache.Redis
卸载这些项目,并在 NuGet 中安装这些模块(搜索“Senparc.Weixin”第一页都在了,认准作者 Jeffrey Su)
单元测试项目中的引用也按需更换,当然也可以卸载这些单元测试项目(视情况保留 Senparc.Weixin.MP.Sample.Tests) 。
【可能】运行报错
HTTP Error 500.19 - Internal Server Error
无法访问请求的页面,因为该页的相关配置数据无效。
配置源:
134: </sessionState>
135: <sessionState customProvider="Memcached" mode="Custom">
136: <providers>
可以在 Global.asax 的 RegisterWeixinCache() 中修改 Memcached 配置。
或者打开 Web.config,找到 Memcached 所在的 sessionState 标签,注释掉,这样程序自动使用上方的 InProc(应用进程内)。
如果开启了 ASP.NET State Service 服务,那么建议改用 StateServer,与 Custom 一样需要序列化,方便日后改用 Memcached 或 Redis。
再次更新 NuGet,否则会提示无法加载 Enyim.Caching 的错误(报错行:MemcachedObjectCacheStrategy.RegisterServerList(memcachedConfig);)。
接下来,进入微信公众平台,在左侧 开发 - 基本配置 中设置相关参数(填写“服务器地址(URL)”如“https://weixin.xoyozo.net/weixin/”),打开 Sample 项目中的 Web.config,配置我们的公众号参数。
将项目发布到服务器上,尝试向公众号发送消息吧。
单元测试
设置单元测试中的公众号配置项:打开 Senparc.Weixin.MP.Test/CommonAPIs/CommonApiTest.cs,在 AppConfig 方法中可以看到支持两种配置方式,在 Senparc.Weixin.MP.Test/Config/test.config 配置文件中配置,或直接在 CommonApiTest.cs 文件中配置,前者格式如下,后者建议只在个人测试项目中使用。
<Config> <AppId>YourAppId</AppId> <Secret>YourSecret</Secret> <MchId>YourMchId</MchId> <TenPayKey>YourTenPayKey</TenPayKey> <TenPayCertPath>YourTenPayCertPath</TenPayCertPath> <!-- 小程序 --> <WxOpenAppId>YourOpenAppId</WxOpenAppId> <WxOpenSecret>YourWxOpenSecret</WxOpenSecret> </Config>另外,将 _testOpenId 值改为自己的微信号在本公众号上的 openid。
微信网页授权(OAuth2)
打开 OAuth2Controller 控制器,将“Index”Action 中的盛派的网址(有 2 处)改成:
Request.Url.Scheme + "://" + Request.Url.Authority + "/Oauth2/……未完待续……
HTML5 Sortable 是一款使用原生 HTML5 drag 和 drop API 来对列表或网格进行排序的 jQuery 插件。
下载和使用:官网
步骤:
1、给 <ul /> 添加 sortable 样式类
2、引入 jquery.sortable.js
3、$('.sortable').sortable();
通过绑定 sortupdate 事件来获取排序后的 DOM 位置,示例:
$('.sortable').sortable().bind('sortupdate', function (event, ui) {
var item = $(ui.item[0]);
var prev = item.prev();
$.post(window.location.pathname, {
xdo: 'fn_sort',
cid: item.data('cid'),
prev: prev.data('cid') // 可能为 undefined
}, function (json) {
if (json.result.success) {
} else {
toastr['error'](json.result.info);
}
}, 'json');
});
解决方法:安装最新的 .NET Core runtime 即可:https://www.microsoft.com/net/download/core#/runtime
(Windows Server 上选择 Windows Server Hosting (x64 & x86))
如果我们直接更改模型的属性名,在迁移的时候会报错:
Data\DbInitializer.cs(,): error CS0117: '表' does not contain a definition for '新列名'
原因是它无法判断是把什么列名更改为什么列名(比如一次改多列呢),那么我们需要用 [Column("列名")] 来映射
方法一:
先加上 [Column("新列名")] ,执行迁移
再修改模型的属性名并删除 [Column("新列名")],执行迁移
方法二:
先加上 [Column("原列名")] ,同时修改模型的属性名,执行迁移,
再删除 [Column("原列名")],执行迁移