Hakim al-Umma Hadhrat Mawlana Ashraf ‘Ali Thanawi (may Allah have mercy on him) said,
“Occasionally these unintentional bad thoughts (khatarat) are due to an extra sensitive psyche and personality. Some times they are due to medical reasons. At other times they are due to acts of blame worthy moral traits. On other ocasions it may be secondary to some evil (Satanic) intervention or sins. Also it may be a test of one’s yearning and desire for Allah’s pleasure. And some times more than one of these may combine.
In a case where a specific reason can not be ascertained it is best to combine all the possible treatments (that are: repentance, firm reslove of being upright in future, treatment for medical, psychological and magic/evil-eye illnesses, excessive supplication and turning to Allah).
However, in all cases in addition to the specific treatment the common remedy for all cases is not to pay any attention to these thoughts. Do not contemplate on the nature or the reason for these bad thoughts.”
Ashraf us Sawnih, volume 1, page 434