[Solved] Error: Can't call View#subscribe from inside the destroyed callback, try calling it inside created or rendered

  • I have a Tracker.autorun with a subscription in it

  • The subscription call takes a few parameters. It takes a radius in miles (from a slider ui component), and it takes a few other parameters too

  • It all works great, but unfortunately I get this error… and while everything still works in chrome, this error seems to crash safari.

Error: Can't call View#subscribe from inside the destroyed callback, try calling it inside created or rendered.

I found this: Problem with template subscription

moving the session variables and reactiveVars into variables outside of the autorun function gets rid of the error, but then the subscription isn’t reactive anymore.

Original:

Template.MyTemplate.onCreated( function() {

    var template = Template.instance();

    template.searchQuery = new ReactiveVar();

    Tracker.autorun( function () {

        // calls subscription and sends the geo-radius as a param
        template.subscribe( 'myLocationBasedSubscription', template.searchQuery.get(),)

    });

});


Template.MyTemplate.events({
    // LOCATION
    'change [name="search"]' ( event, template ) {
        let value = event.target.value.trim();
        template.searchQuery.set( value );
    },
});

new code that isn’t reactive anymore:

Template.MyTemplate.onCreated( function() {

    var template = Template.instance();

    template.searchQuery = new ReactiveVar();

var theQueryNeeded =  template.searchQuery.get();

    Tracker.autorun( function () {

        // calls subscription and sends the geo-radius as a param
        template.subscribe( 'myLocationBasedSubscription',theQueryNeeded)

    });

});

Try this

Template.MyTemplate.onCreated( function() {
    var template = this;

    template.searchQuery = new ReactiveVar();

    template.autorun( function () {
        // calls subscription and sends the geo-radius as a param
        template.subscribe( 'myLocationBasedSubscription', template.searchQuery.get(),)
    });
});

Template.instance() is only used in helpers

2 Likes

Oddly, it seems to work with either this or Template.instance()

It seems the issue was Tracker.autorun-- which should have been template.autorun

you can see it brought up here in the comments: https://themeteorchef.com/snippets/simple-search/