Why a person may have a temptation to do something unrelated when doing especially important thing? I would like to know, why a person may have a temptation to do something unrelated (or slightly related to his current task) when doing particularly important job? 

Like, when preparing for an important math test under a time pressure, to spend time on consulting grammar book on why some sentence were constructed in that particular way and what are the rules for constructing the sentences of this kind, then finding some question while studying this and switch to stydying the new question and so on. As a result spending much more time on "unrelated" things rather than on the important one?

What mechanisms lie behind this behaviour? Is there a scientific description of this phenomenon?

I'll rephrase the initial question:
Why a person may have a strong subconscious temptation to distract oneself from doing very important job?
This is a partial answer to your question.

It is something that I do frequently - often it is a case of having several tasks that must be done in varying degrees of important and urgency.  What seems to happen is that the main, most urgent, task is 'deferred' whilst performing the less urgent and less important smaller tasks - effectively shrinking the 'to do' list.

A phenomena that seems to relate to what you are asking is known as 'mind-wandering', in the article "Tracking the train of thought from the laboratory into everyday life:
An experience-sampling study of mind wandering across
controlled and ecological contexts", (McVay et al. 2009), asserts that mind wandering is symptomatic of people being unaware of conscious activity.  That mind-wandering


  increasing with stress, boredom, sleepiness, or chaotic environments, and
  decreasing with concentration, effort, successful performance, enjoyable tasks, or happiness.


Also, according to the article "The Importance of Mind-Wandering", (Lehrer, 2011), assert that,


  Activation in medial prefrontal default network regions was observed both in association with subjective self-reports of mind wandering and an independent behavioral measure (performance errors on the concurrent task).


In the article, there is a suggestion that normally opposing neural systems ('executive' and 'default') work cooperatively.

So, while it may seem as self-distraction or procrastination, it appears to happen often and is a normal function.